Jquery 多个不需要的旋转

Jquery multiple unwanted 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/

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

要解决此问题,您可以使用 data 属性在每个元素的基础上关联一个 rotation 值,如下所示:

$.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>

另请注意,我向您的 $.rotate 插件添加了一个 return 语句,以便您可以继续从响应链接方法。

另一种解决方案是您可以使用 data-click 属性和 attr() jQuery.

在元素上使用 click 计数

堆栈片段

$("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)"
  });
});
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);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<br>
<div></div>