如何在悬停时添加暂停(jquery)

422*_*422 2 jquery

这是代码:

   $(document).ready(function(){
    $('#testimonials .slide');
    setInterval(function(){
        $('#testimonials .slide').filter(':visible').fadeOut(1000,function(){
            if($(this).next('li.slide').size()){
                $(this).next().fadeIn(2000);
            }
            else{
                $('#testimonials .slide').eq(0).fadeIn(2000);
            }
        });
    },1000);    
}); 
Run Code Online (Sandbox Code Playgroud)

这适用于ul列表,并希望在悬停时添加暂停.有什么建议.?

Luk*_*ger 6

您需要保存返回的对象,setInterval然后您可以将其传递给它clearInterval以阻止它再次发生.

这里有一些示例代码可以让您获得类似于以下内容的代码:

$(document).ready(function(){
    var slider = function() {
        $('#testimonials .slide').filter(':visible').fadeOut(1000,function(){
            if($(this).next('li.slide').size()){
                $(this).next().fadeIn(2000);
            }
            else{
                $('#testimonials .slide').eq(0).fadeIn(2000);
            }
        });
    };

    // save an object so that I can start and stop this as we go
    var interval = setInterval(slider, 1000);

    // when the user hovers in, clear the interval; if they hover out,
    // restart it again
    $('#testimonials .slide').hover(function() {
        clearInterval(interval);
    }, function() {
        interval = setInterval(slider, 1000);
    });
}); 
Run Code Online (Sandbox Code Playgroud)

请注意,这不是很清楚,我什么确切用户将鼠标悬停获得间隔停下来,所以我估计你想$('#testimonials .slide')这样做.如果没有,只需将该部分更改为您需要的任何部分.