gpt4 book ai didi

javascript - 在所有旋转完成后,如何停止我的 html 图像旋转?

转载 作者:行者123 更新时间:2023-11-28 04:33:55 24 4
gpt4 key购买 nike

我有这个code每当用户单击图像时,它都会尝试旋转图像。如果用户单击图像一次并且不再单击它,它会像我预期的那样在尝试一次后停止旋转。然后他们可以再次单击图像,它会再次旋转。

但是,如果他们单击图像一次然后再次单击它,速度会加快,这也是正确的行为。但它永远不会停止旋转。

    if(degree === 361){
clearInterval($this.data('rotating'));
$this.data('rotating', false);
$this.data('degree', 0);
return;
}

此代码应在第二次旋转结束后停止旋转,但它会无限期地继续旋转。我怎样才能让它加速,然后在每次点击的最后一次旋转完成后停止旋转?

最佳答案

这是你的问题:

当您单击它时,您将 setInterval 返回的值分配给元素的数据属性。这会破坏您之前存储的所有 setInterval 值,因此它们永远不会被清除。当你开始一个新的时,不要破坏最后一个,你需要把它们全部存储起来。您可以通过将每个新值插入数组,然后弹出数组的最后一个值并在每次需要清除时清除该值来完成此操作。

( fiddle :http://jsfiddle.net/hmN7a/8/)

$(function() {

var $rota = $('.spin')
var rotating=[];
$rota.click(function(){
var $this = $(this);
//push the latest interval id onto the array
rotating.push(setInterval(function(){
var degree = $this.data('degree') || 0;
if(degree === 361){
clearInterval(rotating.pop()); //clear out the latest inerval in the array
$this.data('rotating', false);
$this.data('degree', 0);
return;
}
$this.css({ transform: 'rotate(' + degree + 'deg)'});
$this.data('degree', ++degree)
}, 5));

});

});

关于javascript - 在所有旋转完成后,如何停止我的 html 图像旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24645613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com