Onmouseover在元素上悬停时多次运行?

时间:2012-02-22 00:24:42

标签: javascript jquery

当我将鼠标悬停在一个元素上时,为什么onmouseover会多次运行?

当用户将鼠标悬停在某个图标上但它会多次运行时,我正在尝试运行一个简单的动画。

我在这里测试它:

http://lujanventas.com/test.php

无论如何,有关如何解决它的任何想法?也许使用听众呢?

这是运行onmouseover的javascript:

function upIcon(n) {
    console.log("Mouseover icon: " + n);
    $('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 );
    $('#icon' + n).animate({ backgroundPositionY : "+=15px" }, 200 );
    }

4 个答案:

答案 0 :(得分:23)

尝试使用mouseentermouseleave代替mouseovermouseout。前者仅在光标进入元素区域时触发,后者在光标在后代之间移动时触发。

我通过我的控制台将此代码添加到您的页面,它按预期工作:

//bind an event handler to each nav element for the mouseenter event
$('.categoryButtons').children().bind('mouseenter', function () {

    //call the `upIcon` function with the index of the current element
    upIcon(($(this).index() + 1));
});

我还删除了每个导航项的内联onmouseover代码。

更新

您可以稍微使用现有函数,不要对事件处理程序使用匿名函数(注意函数链接以避免重复选择):

function upIcon(event) {
    var n = ($(this).index() + 1);
    $('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 ).animate({ backgroundPositionY : "+=15px" }, 200 );
}

$('.categoryButtons').children().bind('mouseenter', upIcon);

当您将现有函数作为事件处理程序引用时,它会像任何其他事件处理程序一样传递event对象,您还可以使用this来引用触发事件的元素

答案 1 :(得分:3)

有几件事:

  • 为了解决您的问题,我会使用mouseenter事件 - 这意味着当鼠标进入元素时代码被执行,然后您可以使用mouseleave在鼠标指针离开时再次更改动画。

  • 不是使用凌乱的onmouseover事件,而是使用jQuery来实现它的意图 - 不引人注目的代码。将事件绑定到元素,例如

    $(document).ready(function() {
         $(".icon").mouseenter(function() {
              $(this).animate({ backgroundPositionY : "-=15px" }, 200 );
         });
    
         $(".icon").mouseleave(function() {
              $(this).animate({ backgroundPositionY : "+=15px" }, 200 );
         });
    
    
    });
    

答案 2 :(得分:1)

由于您使用的是jQuery,因此可以使用mouseenter代替mouseover - 它旨在保护您免受当前目标中有多个项目时的鼠标输出事件的影响。

更多:http://api.jquery.com/mouseenter/

所以,你想要删除附加到每个项目的事件(首先不是很好的形式,而是在脚本块中执行以下操作:

$('.categoryButtons').find('a').mouseenter(function(){
    /* ... Do something, probably depending on $(this).attr('id') or $(this).attr('rel') ... */
});

答案 3 :(得分:1)

我建议使用JQuery的mouseenter来避免因事件冒泡而多次触发处理程序,而不是使用onmouseover:

http://api.jquery.com/mouseenter/