jQuery鼠标悬停在mouseout上运行

use*_*474 5 javascript jquery

这是我的jQuery

$('#samsungShine').mouseover(function () {
    $('#samsungShineImage').animate({
        "margin-left": "304px"
    }, 700);
}).mouseout(function () {
    $('#samsungShineImage').css("margin-left", "-304px");
});
Run Code Online (Sandbox Code Playgroud)

当我鼠标移动时,它工作得非常好,当我鼠标移除时,它没有重置,它重新播放鼠标悬停...这里是问题的小提示,所以你可以看到我的意思:

http://jsfiddle.net/2tujd/

Amy*_*Amy 8

尝试mouseentermouseleave不是:http://jsfiddle.net/2tujd/11/

$('#samsungShine').mouseenter(function () {
    $('#samsungShineImage').animate({
        "margin-left": "304px"
    }, 700);
}).mouseleave(function () {
    $('#samsungShineImage').stop().css("margin-left", "-304px");
});
Run Code Online (Sandbox Code Playgroud)

jQuery网站上,它说关于使用mouseout和simliarly mouseover:

由于事件冒泡,此事件类型可能会导致许多麻烦.例如,当鼠标指针在此示例中移出Inner元素时,将向其发送mouseout事件,然后逐渐向外传递.这可以在不合适的时间触发绑定的mouseout处理程序.

编辑:添加.stop()内部mouseleave以确保在设置之前停止任何当前动画margin-left.

  • 在你的jsfiddle,如果我重复和快速地进入/离开图像,动画不再有效,这就是为什么你应该使用停止 (3认同)

A. *_*lff 4

尝试一下,stop也使用:

演示版

$('#samsungShine').mouseenter(function() {
    $('#samsungShineImage').animate({"margin-left":"304px"}, 700);
}).mouseleave(function(){
    $('#samsungShineImage').stop().css("margin-left", "-304px");
});
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,因为它会立即取消动画。 (2认同)
  • @iGanja 使用 `on` 可能会“更好”,但如果有帮助的话,这是值得商榷的。我就是喜欢直白点。但你是对的,“stop”的使用非常重要。 (2认同)
  • @iGanja 我不明白你的意思。显式绑定是绑定事件处理程序的“长”方式。它们是内部调用“on”的特殊情况,因此它们在技术上更慢(尽管“更慢”可以忽略不计......但是,它们并不是“更快”)。它们所做的与“on”没有什么不同。此外,显式绑定需要链接多个事件(此问题/答案需要),而“on”可以在单个调用中完成,可能更有效。 (2认同)