如何在hover时停止jQuery函数?

我有一个在setInterval()上运行的jQuery函数; 我想要做的是当我将鼠标hover在正在显示的div上时停止间隔,并且一旦我将鼠标hover在div上,再次开始间隔(也就是继续循环通过div)。

关于如何以最简单的forms做到这一点的任何想法?

谢谢! 阿米特

有Reigel的方式 ,它可以处理,或者当然只是设置一个你的函数检查的标志,只有在没有设置标志时才进行处理。 如果已经有一些可以使用的hover指示(例如,与实际的专用标志相反),如果你想在几个时间间隔内执行此操作,则特别方便等。

var hovering = false; function theFunctionRunningOnInterval() { if (!hovering) { // ... } } 

然后把它连接起来,基本上:

 $("selector for your hover elements").hover( function() { hovering = true; }, function() { hovering = false; } ); 

请注意,那些不会声明自己 hovering ,如下面的Amit的评论那样; 它们使用在封闭范围内声明的hovering

更全面的例子:

我在这里使用了一个计数器而不是一个简单的旗帜,但那是我的偏执狂。

HTML:

     Test Page    

Watch the ticker:
...as you move the mouse over and off any of these boxes:

JavaScript(ticktock.js):

 // A scoping function to avoid creating global variables (function() { // Counter for the number of hovering elements var hovering = 0; // Hook up our hover element. I always use named functions, but you could // put anonymous ones here instead. $(".hoverEffect").hover(startHover, endHover); // Start the ticker. Again, a named function, but that's style/debugging, not critical. setInterval(ticker, 500); /** * ticker: Updates the "ticker" element with the tick count and time. */ function ticker() { var tickElement; // Anything hovering? if (hovering > 0) { // Yes, don't do anything return; } // Tick/tock // If you were really doing this every half second, it would be worth // caching the reference to this ticker somewhere rather than looking it up every time tickElement = $("#ticker"); tickElement.html(tickElement.html() === "tick" ? "TOCK" : "tick"); } /** * startHover: Called when any "hoverEffect" element receives a mouseenter event */ function startHover() { // Increment the hovering flag ++hovering; } /** * endHover: Called when any "hoverEffect" element receives a mouseleave event */ function endHover() { // Decrement the hovering flag, clamping at zero out of paranoia if (hovering > 0) { --hovering; } } })(); 
 var interval = setInterval(...) // create the interval clearInterval(interval) // clear/stop interval in some point where you call it... 

调用clearInterval()时,请确保该interval不在范围之外

使用clearInterval函数