javascript - 如何让 SetInterval 在悬停关闭时停止?

标签 javascript jquery hover slideshow setinterval

我有一堆从 YouTube 引入的图像,我希望顶部图像在悬停时淡出,然后开始旋转播放接下来的 3 张图像。我几乎已经可以正常工作了,但是当我将鼠标悬停在缩略图上时,我遇到了让 SetInterval 停止的问题。

thumbRotate: function(){} //This is up in the main object

//hover state over thumbs and slideshow animation       
$('#youtube-widget ul a').hover(
    // hover-in
    function(){
        $this = $(this);

        $(this).children('.title-overlay').children('h5, img, span').stop(true, true).animate({opacity: '0'}, 200, function() {
            $.Modules.VideoWidget.thumbRotate = setInterval(function() { 
                var topImage = $this.children('img:first');
                topImage.stop(true, true).fadeOut(500).next().stop(true, true).fadeIn(500).end().appendTo($this);
            }, 2000);
        });
    //hover-out 
    }, function() {
        clearInterval($.Modules.VideoWidget.thumbRotate);
        $(this).children('.title-overlay').children('h5, img, span').stop(true, true).animate({opacity: '1'}, 200);
    }
);

编辑:我注意到将鼠标悬停在缩略图上似乎会呈指数级增加动画。由于某种原因,动画似乎会自行堆积,但我不太明白为什么。

最佳答案

这是问题 - .hover() 和 .mouseover()... 这两个函数不仅在光标进入元素时执行操作,而且在每次鼠标在元素内移动单个像素时执行操作。换句话说,这两个函数非常适合简单的交互,但有必要使用 .mouseenter() 和 mouseleave() 来设置间隔函数,否则每次光标在元素内移动时,您最终都会设置一个新的间隔(这可以是很多)。

新 fiddle - http://jsfiddle.net/b3Mb8/2/ 新代码 -

//thumb rotate animation on hover
function startRotate($this) {
    $.Modules.VideoWidget.thumbRotate = setInterval ( function() { 
        topImage = $this.children('img').filter(":first");
        topImage.animate({opacity: '0'}, 500).next().animate({opacity: '1'}, 500).end().appendTo($this);                                        
    }, 800);
}
function stopRotate() {
    clearInterval($.Modules.VideoWidget.thumbRotate);
}

$("#youtube-widget ul a").mouseenter(function() {               
    $this = $(this);
    startRotate($this);                     
}).mouseleave(function() {              
    stopRotate();               
});

//hover state over thumbs and slideshow animation       
$('#youtube-widget ul a').hover( function(){
    $this.children('.title-overlay').children('h5, img, span').stop(true, true).animate({opacity: '0'}, 300, function() {
    });
//hover-out 
}, function() {
    $this.children('.title-overlay').children('h5, img, span').stop(true, true).animate({opacity: '1'}, 300);
});

关于javascript - 如何让 SetInterval 在悬停关闭时停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435812/

相关文章:

javascript - 鼠标悬停消息显示在图像的某些部分 jquery/js

javascript - 从类方法中使用jquery悬停

javascript - .innerHTML 未显示

javascript - CakePHP 和 JQuery,location.reload 有时不工作

javascript - javascript 中 >> 和 >>> 运算符有什么区别

jquery - 在 wordpress 中添加自定义帖子类型

jquery - 具有淡入淡出效果的图像悬停 - 使它们居中

javascript - 如何在网页中预览上传的视频

html - CSS :hover not working on iOS Safari and Chrome

javascript - 如何将路由器放入路由器内部