元素悬停时的暂停功能

Pause function on element hover

本文关键字:暂停 功能 悬停 元素      更新时间:2023-09-26

我有一个图像滑块,它每5秒更改一次图像,但我希望当我将光标悬停在div img上时,滑块会暂停。有没有办法在悬停时暂停"旋转器"功能,然后在鼠标移出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
});

您需要检索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
});

您只需要清除mouseover上的超时,然后在mouseout上重新创建它,如下所示:

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);
    });
});

你可以做一些类似的事情

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

并在rotate()函数中检查该标志