所有旋转完成后如何阻止我的html图像旋转?

时间:2014-07-09 04:50:16

标签: javascript jquery html

我有这个code尝试在用户点击图片时旋转图像。如果用户单击图像一次并且没有再次单击它,则会在我想要的一次尝试后停止旋转。然后他们可以再次点击图像,它会再次旋转。

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

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

此代码应在第二次旋转结束后停止旋转,但它会继续无限旋转。如何在每次点击最后一次旋转完成后加速然后停止旋转?

3 个答案:

答案 0 :(得分:6)

这是你的问题:

单击它时,您将setInterval返回的值分配给元素的data属性。这会破坏您存储的任何先前setInterval值,因此它们永远不会被清除。每当你开始一个新的时候,你需要将它们全部存储起来,而不是破坏最后一个。您可以通过将每个新值推送到数组上来完成此操作,然后弹出数组的最后一个值,并在每次需要清除时清除该值。

(小提琴: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));

    });

});

答案 1 :(得分:2)

尝试添加此代码以停止轮换:

    if($this.data('rotating')) {
        $this.css({ transform: 'rotate(' + degree + 'deg)'});
        $this.data('degree', ++degree)
    }

这是一个小提琴:http://jsfiddle.net/hmN7a/6/

希望这有帮助。

答案 2 :(得分:-1)

使用clearInterval函数。

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

http://jsfiddle.net/SkUV9/