2012-02-11 150 views
2

我有一个图像滑块,每5秒更换一次图像,但我希望滑块在我停留在div img时暂停。有没有办法在悬停时暂停'theRotator'函数,然后在鼠标移出div后重新启动它?谢谢大家!元素悬停时暂停功能

function theRotator() { 
    //Set the opacity of all images to 0 
    $('div.rotator ul li').css({opacity: 0.0}); 

    //Get the first image and display it (gets set to full opacity) 
    $('div.rotator ul li:first').css({opacity: 1.0}); 

    //Call the rotator function to run the slideshow, 

    setInterval('rotate()',5000); 

} 

$(document).ready(function() {  
    //Load the slideshow 
    theRotator(); 
    $('div.rotator').fadeIn(1000); 
    $('div.rotator ul li').fadeIn(1000); // tweek for IE 
}); 
+0

出于某种原因,我认为你跑了两次,为什么? 我觉得你应该这样做,运行.delay() - >在jquery.com上阅读它。 – IamStalker 2012-02-11 22:31:03

回答

0

你只需要清除鼠标悬停超时,然后重新创建鼠标移开时,这样:

var interval; 

function theRotator() { 
    $('div.rotator ul li').css({opacity: 0.0}); 
    $('div.rotator ul li:first').css({opacity: 1.0}); 
    interval = setInterval(rotate, 5000); 
} 

$(document).ready(function() { 
    theRotator(); 
    $('div.rotator').fadeIn(1000); 
    $('div.rotator ul li').fadeIn(1000); // tweek for IE 

    $('div.rotator ul li').hover(function() { 
     clearInterval(interval); 
    }, 
    function() { 
     interval = setInterval(rotate, 5000); 
    }); 
}); 
+0

看起来我留下了一块,再试一次... – ajodom10 2012-02-11 22:45:15

+0

这工作,谢谢! – ajodom10 2012-02-11 22:51:01

1

您需要检索setInterval函数返回的间隔句柄。此外,我使用mouseentermouseleave,因为它们更适合您所需的功能。

function theRotator() { 
    //Set the opacity of all images to 0 
    $('div.rotator ul li').css({opacity: 0.0}); 

    //Get the first image and display it (gets set to full opacity) 
    $('div.rotator ul li:first').css({opacity: 1.0}); 

    //Call the rotator function to run the slideshow, 

    window.rotatorInterval = setInterval(rotate,5000); 
} 

$(document).ready(function() { 

    //Load the slideshow 
    theRotator(); 

    $('div img').mouseenter(function(){ 
     clearInterval(window.rotatorInterval); 
    }).mouseleave(function() { 
     window.rotatorInterval = setInterval(rotate, 5000); 
    }); 

    $('div.rotator').fadeIn(1000); 
    $('div.rotator ul li').fadeIn(1000); // tweek for IE 
}); 
0

你可以做类似

var rotate = true; 

$('img').on({ 
    mouseenter: function() { 
     rotate = false; 
    }, 
    mouseleave: function() { 
     rotate = true; 
    } 
});​ 

,并检查标志在你rotate()功能