lis*_*aro 14 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 );
}
Run Code Online (Sandbox Code Playgroud)
Jas*_*per 23
尝试使用mouseenter而mouseleave不是mouseover和mouseout.前者仅在光标进入元素区域时触发,后者在光标在后代之间移动时触发.
我通过我的控制台将此代码添加到您的页面,它按预期工作:
//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));
});
Run Code Online (Sandbox Code Playgroud)
我还删除了onmouseover每个导航项的内联代码.
您可以稍微使用现有函数,而不是对事件处理程序使用匿名函数(注意函数链接以避免重复选择):
function upIcon(event) {
var n = ($(this).index() + 1);
$('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 ).animate({ backgroundPositionY : "+=15px" }, 200 );
}
$('.categoryButtons').children().bind('mouseenter', upIcon);
Run Code Online (Sandbox Code Playgroud)
当您将现有函数作为事件处理程序引用时,它会event像任何其他事件处理程序一样传递对象,您还可以使用它this来引用触发事件的元素.