我的代码有问题。我的页面上有多个 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
最佳答案
问题是因为您正在增加全局 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/