悬停时停止循环 [英] Stop loop on hover

查看:66
本文介绍了悬停时停止循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery在列表ul上循环addClassremoveClass函数.

I am using jQuery to loop an addClass and removeClass function on a list ul.

$(function () {
  var $looped = $('li');

  (function _loop(idx) {
    $looped.removeClass('current').eq(idx).addClass('current');
    setTimeout(function () {
      _loop((idx + 1) % $looped.length);
    }, 1000);
  }(0));
});

我想在用.mouseenter()悬停元素时停止此循环,以使用户自己控制该示例.

I want to stop this loop while I am hovering the element with .mouseenter() to let the user control this example on his own.

JSFiddle演示视图

使用 Tobia Pause插件即可轻松实现,但遗憾的是,这仅对animate()循环.我感谢所有提示或提示!

This is quite easy to achieve with Tobia Pause Plugin, but sadly this does only work for animate() loops. I appreciate every hint or tip!

推荐答案

在此示例中,我演示了如何在hover()事件上暂停和重新启动动画.这也将重新启动动画,使其完全从中断处开始.

In this example, I've shown how to pause and restart the animation on a hover() event. This also restarts the animation exactly where it left off.

$(function () {
    var $looped = $('li');
    var timeOut;
    var index = 0;
    function _loop(idx) {
        $looped.removeClass('current').eq(idx).addClass('current');
        timeOut = setTimeout(function () {
            index = (idx + 1) % $looped.length;
            _loop(index);
        }, 1000);
    };
    _loop(index);
    $("ul").hover(function () {
        window.clearTimeout(timeOut);
    }, function () {
        _loop(index);
    });
    $("li").hover(function () {
        $("li").removeClass("current");
        $(this).addClass("current");
    }, function () {
        $("li").removeClass("current");
    });
});

有几个关键点.

首先-我在跟踪超时功能的匿名函数中分配了一个 函数作用域 变量(不是全局变量).这使我以后可以在该功能中清除它.不必要地弄乱全局名称空间通常是一个坏主意.

First - I assign a function-scoped variable (not global) within the anonymous function that tracks the timeout function. This allows me to clear it at a later time within that function. It's typically a bad idea to clutter up the global namespace unnecessarily.

第二个-我将mouseenter()函数更改为hover()函数,该函数接受两个函数作为参数,一个用于鼠标移过,另一个用于鼠标移出事件.

Second - I changed the mouseenter() function to a hover() function, which accepts two functions as parameters, one for the mouse over, and one for the mouse out events.

第三-我添加了一个名为index的变量,它将在整个函数中为我们跟踪索引.这样,当鼠标不再位于元素上时,循环就可以精确地从中断处恢复.

Third - I added in a variable called index which is going to keep track of the index for us throughout the function. This allows the loop to resume exactly where it left off when the mouse is no longer over the element.

请参见 小提琴在这里

See the Fiddle HERE

这篇关于悬停时停止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆