javascript 悬停时的jQuery暂停功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4766163/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery pause function on hover?
提问by
I have a jQuery/JS function that is using setIntervalto loop through some image slides I have.  It just flips through every 5 seconds...
我有一个 jQuery/JS 函数,setInterval用于循环浏览我拥有的一些图像幻灯片。它只是每 5 秒翻一次...
Now I want it to pause if my mouse is hovered over it. How do I go about doing that on the setInterval function?
现在,如果我的鼠标悬停在它上面,我希望它暂停。我该如何在 setInterval 函数上做到这一点?
var current = 1;
function autoAdvance() {
    if (current == -1) return false;
    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}
// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);
采纳答案by Jacob Relkin
Something like this would work assuming intervalis defined in an outer scope:
假设interval在外部范围中定义了这样的东西:
$('.slideshow img').hover(function() {
  interval = clearInterval(interval);
}, function() {
  interval = setInterval(flip, 5000);
});
回答by Reid
(function () {
    var imgs = $('#your_div img'), index = 0, interval,
        interval_function = function () {
            imgs.eq(index).hide();
            index = (index + 1) % imgs.length;
            imgs.eq(index).show();
        };
    imgs.eq(0).show();
    interval = setInterval(interval_function, 5000);
    $('#your_div').hover(function () {
        clearInterval(interval);
    }, function () {
        interval = setInterval(interval_function, 5000);
    });
}());
Example: http://jsfiddle.net/Zq7KB/3/
示例:http: //jsfiddle.net/Zq7KB/3/
I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.
我重用了一些我前几天为一个问题编写的旧代码,但我认为这没有那么重要。诀窍是将您的间隔存储在您保留在后台的变量中。然后,当您将鼠标悬停在容器上时,清除间隔。当您将鼠标悬停在容器外时,请重新设置间隔。为了更好地了解它是如何工作的,请将这些5000s更改为1000s 以便更快地通过测试。
Hope this helps.
希望这可以帮助。

