Jquery 多次不需要的旋转

标签 jquery css animation rotation

我的代码有问题。我的页面上有多个 block ,并且我希望每个 block 独立于其他 block 旋转。此 jQuery 代码管理该操作,但也更新变量“旋转”,以便下一个 block 旋转 180 + 180*n('n' = 当前 block 旋转的倍数)

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

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”个单独的 block ,它们只能旋转 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 语句,以便您可以继续从响应中链接方法。

关于Jquery 多次不需要的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48561677/

相关文章:

javascript - Jquery 设置不同的输入文本和值

javascript - 12 小时 Javascript 时钟显示 24 时间,错误的 AM/PM

javascript - 如何使用 onclick 事件链接到网页而不是 href?

相对于图像的 HTML/CSS 文本

cocoa-touch - 在 iOS 上创建动画的简单方法?

python - Jupyter notebook 中的 Matplotlib 动画创建额外的空图

javascript - 将多维 JSON 数组转换为 JS 变量

html - CSS:包含文本节点的第一个 child 选择器

html - 工具提示被 div 容器截断

CSS3 Animation + @keyframe 运行到最后