如何告诉Jquery只运行最后一个mouseenter事件

How to tell Jquery to run only the last mouseenter event?

本文关键字:最后一个 mouseenter 事件 运行 何告诉 Jquery      更新时间:2023-09-26

我有一组幻灯片,当鼠标进入幻灯片图像时,我想放大照片。

当我把鼠标放在图像上时,所有的图像都按照我把鼠标移到的顺序放大。如何强制jquery只超过最后一个鼠标输入事件并取消所有历史鼠标输入事件

这是我的jquery代码。

$(document).ready(function(){
        $("#hoverslider ul li").bind("mouseenter",function(){
            $(this).animate({
                width:"500px"
            },"slow");
            $(this).addClass("active");
            $("#hoverslider ul li:not(.active)").animate({
                width:"141px"
            });
            })
       $("#hoverslider ul li").bind("mouseleave",function(){
            $(this).animate({
               width:"213px"
            },"slow");
           $(this).removeClass("active");
           $("#hoverslider ul li:not(.active)").animate({
               width:"213px"
           });
       });
});

请帮我渡过难关。谢谢

您最初可以停止mouse enter中的所有animations,并为鼠标当前所在的图像设置动画,但请记住,在mouseleave中启动动画之前,您不应该stop动画(所有元素,而不是单个元素),因为这将有助于元素恢复到旧状态。

工作演示

试试这个,

$(document).ready(function(){
        $("#hoverslider ul li").bind("mouseenter",function(){
            $("#hoverslider ul li").stop();
            $(this).stop().animate({
                width:"500px"
            },"slow");
            $(this).addClass("active");
            $("#hoverslider ul li:not(.active)").stop().animate({
                width:"141px"
            });
            })
       $("#hoverslider ul li").bind("mouseleave",function(){
            $(this).stop().animate({
               width:"213px"
            },"slow");
           $(this).removeClass("active");
           $("#hoverslider ul li:not(.active)").stop().animate({
               width:"213px"
           });
       });
});

您可以使用setTimeout()来触发放大动画。在mouseenter事件处理程序中,如果上一个动画尚未启动,请使用clearTimeout()取消它。

这样鼠标的快速移动不会触发所有图像放大。

我不完全理解你的问题,但似乎你可以用这种方式使用hover方法

$( "#hoverslider ul li" ).hover(
        function(){
            $(this).animate({
                width:"500px"
            },"slow");
            $(this).addClass("active");
            $("#hoverslider ul li:not(.active)").animate({
                width:"141px"
            });
    },
    function(){
        $(this).animate({
               width:"213px"
        },"slow");
        $(this).removeClass("active");
        $("#hoverslider ul li:not(.active)").animate({
               width:"213px"
        });
    }

);

在线查看http://jsfiddle.net/augusto1982/At8XR/

如果这不是你需要的,请告诉我,我会解决的。

您可以使用下划线辅助方法debounce

http://underscorejs.org/#debounce

这将为您的回调创建一个包装器,并且在您仍然调用它的时候,每x秒只调用一次。这意味着,您可以有许多鼠标输入,并且该方法只会被调用一次,只有在x秒之后,没有注册鼠标输入,该函数才可以再次调用。

您应该使用jQuery的on方法来添加事件,而不是旧的bind方法。然后可以使用off方法禁用事件处理程序。