连续轮换

时间:2018-10-24 12:44:26

标签: javascript jquery

我在点击时应用了以下代码:

$("#search").click(function()
{
  if (searchForth)
  {
    animateRotate(45,"#search");
    searchForth = false;
  }
  else
  {
    animateRotate(-45,"#search");
    searchForth = true;
  }
});

函数被调用:

function animateRotate(d,element)
{
  var elem = $(element);
  $({deg: 0}).animate({deg: d},{
      duration: 600,
      step: function(now)
      {
        elem.css({
            transform: "rotate(" + now + "deg)"
        });
      }
  });
}

调用函数时,该元素从默认位置旋转45度,这正是我想要的。但是,当我再次单击该元素时,该函数应用了-45度的旋转,但它是从元素的默认位置开始的,而不是从上一次旋转后元素保留在其中的位置。为什么会这样,如何解决这个问题,使第二个动画从第一个动画的最终位置“伸出”呢?

3 个答案:

答案 0 :(得分:0)

  1. 您应该保存旋转角度
  2. 您不应按度数找到elem

var searchForth = false;
var angle=0;
$("#search").click(function()
{
  if (searchForth)
  {
    angle += 45;
    animateRotate(angle,"#search");
    searchForth = false;
  }
  else
  {
    angle -= 45;
    animateRotate(angle,"#search");
    searchForth = true;
  }
});

function animateRotate(d,element)
{
  var elem = $(element);
  $(elem).animate({deg: d},{
      duration: 600,
      step: function(now)
      {
        elem.css({
            transform: "rotate(" + now + "deg)"
        });
      }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="search">Search</button>

答案 1 :(得分:0)

您需要首先获取当前旋转位置,然后根据searchForth的值从该位置添加/删除45度。

查看更多信息:Get element -moz-transform:rotate value in jQuery

var searchForth=false;
$("#rotate").click(function()
{
  if (searchForth)
  {
    animateRotate(45,this);
    searchForth = false;
  }
  else
  {
    animateRotate(-45,this);
    searchForth = true;
  }
});
function animateRotate(d,element)
{
var startDeg = getRotationDegrees($(element));
  var elem = $(element);
  $(elem).animate({deg: (startDeg + d)},{
      duration: 600,
      step: function(now)
      {
        elem.css({
            transform: "rotate(" + now + "deg)"
        });
      }
  });
}

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return (angle < 0) ? angle + 360 : angle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotate">Rotate me!</div>

答案 2 :(得分:0)

仅使用CSS3过渡和转换怎么样?

$(function() {
  var deg = 45;
  var srh = $('#search').on('click', function(e) {
    srh.css('transform', 'rotate(' + (deg) + 'deg)');
    deg = -(deg);
  });
});
#search {
  transition: transform 1s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="search">Search</button>