Jquery多次不需要的轮换

时间:2018-02-01 11:31:03

标签: jquery css css3 animation rotation

我的代码有问题。我的页面上有多个块,我希望每个块与另一个块分开旋转。这个jQuery代码管理它,但也更新变量“rotation”,所以下一个块旋转180 + 180 * n('n'=当前块旋转的时间)

我认为问题在于可变轮换,但不知道任何解决方法。

var rotation = 0;
jQuery.fn.rotate = function(degrees) {
  $(this).css({
    'transform': 'rotate(' + degrees + 'deg)'
  });
};

$('.strijela').click(function() {
  rotation += 180;
  $(this).rotate(rotation);
});
.strijela {
  transition: 0.3s linear;
  background-color: black;
  color: white;
  height: 150px;
  width: 150px;
  margin: 20px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="strijela">this should rotate once when clicked</div>
<div class="strijela">this should also rotate when clicked but only once.</div>

<p>
  problem is, the more you click on first block, second block will rotate that much more times and vice versa. I know it is because of the variable "rotation", but don't know how to solve that problem. Thank you.
</p>

总之,我需要'n'个单独的块,它们只会旋转180°,而不是180 * n

http://jsfiddle.net/Lbq3K/3/

2 个答案:

答案 0 :(得分:3)

问题是因为您正在递增全局data变量,因此任何后续点击任何元素的旋转都会乘以之前的点击次数。

要解决此问题,您可以使用$.fn.rotate = function(degrees) { return $(this).css({ 'transform': 'rotate(' + degrees + 'deg)' }); }; $('.strijela').click(function() { var rotation = $(this).data('rotation') || 0; rotation += 180; $(this).rotate(rotation).data('rotation', rotation) });属性在每个元素的基础上关联.strijela { transition: 0.3s linear; background-color: black; color: white; height: 150px; width: 150px; margin: 20px auto; }值,如下所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="strijela">this should rotate once when clicked</div>
<div class="strijela">this should also rotate when clicked but only once.</div>
return
$.rotate

另请注意,我在if (savedInstanceState == null)插件中添加了onCreate()语句,以便您可以继续从响应中链接方法。

答案 1 :(得分:0)

另一种解决方案是,您可以使用data-click属性和attr() jQuery对元素使用$("div").attr("data-click", 0); $("div").on("click", function() { var click = $(this).attr("data-click"); click++; $(this).attr("data-click", click); $(this).css({ "transform": "rotate(" + 180 * click + "deg)" }); });计数。

Stack Snippet

&#13;
&#13;
div {
  width: 100px;
  height: 100px;
  background: red;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all .3s ease;
}

div:after {
  content: attr(data-click);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<br>
<div></div>
&#13;
{{1}}
&#13;
&#13;
&#13;