Javascript 元素悬停时的暂停功能
我有一个图像滑块,每5秒更改一次图像,但我希望当我将鼠标悬停在div img上时,滑块会暂停。有没有办法暂停鼠标悬停时的“theRotator”功能,然后在鼠标移出div后重新启动它?谢谢大家Javascript 元素悬停时的暂停功能,javascript,jquery,Javascript,Jquery,我有一个图像滑块,每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 i
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
});
您需要检索由
setInterval
函数返回的间隔句柄。另外,我使用了mouseenter
和mouseleave
,因为它们更适合您想要的功能
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
});
你可以这样做
var rotate = true;
$('img').on({
mouseenter: function() {
rotate = false;
},
mouseleave: function() {
rotate = true;
}
});
并在
rotate()
函数中选中该标志,只需清除鼠标上方的超时,然后在鼠标上重新创建超时,如下所示:
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);
});
});
出于某种原因,我想你会运行两次,为什么?我认为您应该做一些类似思考的操作,运行.delay()->在jquery.com上阅读相关内容