我希望html中的div标记可以旋转,当我点击它时。这是我的密码
$(document).on('click', '.rotate', function() {
degrees = 0;
while (degrees >= (-1080)) {
$(this).css({
'transform': 'rotate(' + degrees + 'deg)'
}).css({
'transition': '3s'
});
degrees--;
}
});.rotate {
position: relative;
width: 200px;
height: 200px;
border-radius: 50%;
background: linear-gradient(magenta, blue, cyan, magenta);
margin: 100px auto;
line-height: 100px;
cursor: pointer;
border: 1px solid #fff;
}
.center {
width: 30px;
height: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
border-radius: 50%;
box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.7);
z-index: 5;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rotate">
<div class="center"></div>
</div>
它在第一次点击时效果很好。但在第二次和以后的点击,它没有。我不知道这是为什么会发生。
发布于 2020-03-02 12:40:10
没有必要使用while循环: CSS将直接处理动画,而且您不必在每一步都设置程度。
动画在第一次单击后不再运行的实际原因是,您总是将动画添加到-1080deg,这意味着在第一次运行之后,您将停止更改该值,因为它已经位于-1080deg:由于值从未更改,因此由于浏览器看不到任何差异,因此CSS动画将不再运行,并且将选择不更改任何内容。
您想要的是降低--每个计数/单击--的程度。可以通过存储点击次数来完成,然后在每次单击时增加点击次数。然后,要旋转的度数将是该计数的倍数:
let count = 0;
$(document).on('click', '.rotate', function() {
count++;
degrees = -1080 * count;
$(this).css({
'transform': 'rotate(' + degrees + 'deg)'
}).css({
'transition': '3s'
});
});.rotate {
position: relative;
width: 200px;
height: 200px;
border-radius: 50%;
background: linear-gradient(magenta, blue, cyan, magenta);
margin: 100px auto;
line-height: 100px;
cursor: pointer;
border: 1px solid #fff;
}
.center {
width: 30px;
height: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
border-radius: 50%;
box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.7);
z-index: 5;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rotate">
<div class="center"></div>
</div>
发布于 2020-03-02 12:44:02
首先,您不希望jQuery在while循环中执行动画。
让CSS做动画,只使用jQuery连接事件处理程序,并确保旋转动画不会堆叠。
$(document).on('click', '.rotate:not(.rotating)', function () {
var $this = $(this);
$this.addClass("rotating");
setTimeout(function () {
$this.removeClass("rotating")
}, 3000);
});.rotate {
height: 50px;
width: 50px;
text-align: center;
border: 1px solid blue;
padding: 5px;
margin: 5px;
display: inline-block;
}
.rotating {
transform: rotate(-1080deg);
transition: 3s;
border-color: red;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rotate">rotate 1</div>
<div class="rotate">rotate 2</div>
<div class="rotate">rotate 3</div>
<div class="rotate">rotate 4</div>
https://stackoverflow.com/questions/60488776
复制相似问题