Javascript Onmouseover在元素上悬停时多次运行?
为什么onmouseover在一个元素上运行多次 我尝试在用户将鼠标悬停在图标上时运行一个简单的动画,但它会运行多次 我在这里测试它: 不管怎么说,有没有办法解决这个问题?也许用一个监听器来代替 这是在MouseOver上运行的javascript:Javascript Onmouseover在元素上悬停时多次运行?,javascript,jquery,Javascript,Jquery,为什么onmouseover在一个元素上运行多次 我尝试在用户将鼠标悬停在图标上时运行一个简单的动画,但它会运行多次 我在这里测试它: 不管怎么说,有没有办法解决这个问题?也许用一个监听器来代替 这是在MouseOver上运行的javascript: function upIcon(n) { console.log("Mouseover icon: " + n); $('#icon' + n).animate({ backgroundPositionY : "-=15px" }
function upIcon(n) {
console.log("Mouseover icon: " + n);
$('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 );
$('#icon' + n).animate({ backgroundPositionY : "+=15px" }, 200 );
}
由于您使用的是jQuery,因此可以使用
mouseenter
而不是mouseover
——它旨在保护您在目标中有多个项目时免受mouseout事件的影响
更多:
因此,您希望删除附加到每个项目的事件(这首先不是一个好的形式,而是在脚本块中执行以下操作:
$('.categoryButtons').find('a').mouseenter(function(){
/* ... Do something, probably depending on $(this).attr('id') or $(this).attr('rel') ... */
});
尝试使用
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));
});
我还删除了每个导航项目的内联onmouseover
代码
更新
您可以稍微不同地使用现有函数,而不将匿名函数用于事件处理程序(请注意函数链接以避免重复选择):
当您引用一个现有函数作为事件处理程序时,它会像任何其他事件处理程序一样传递
event
对象,您也可以使用this
引用触发事件的元素。我建议使用JQuery的mouseenter,而不是使用onmouseover,以避免多次触发事件事件冒泡导致的处理程序:
有几件事:
- 为了解决您的问题,我将使用mouseenter事件-这意味着当鼠标进入元素时,代码将被执行,然后当鼠标指针离开时,您可以使用mouseleave再次更改动画
- 与使用凌乱的onmouseover事件相比,您最好使用jQuery来了解它的用途——不引人注目的代码
$(document).ready(function() { $(".icon").mouseenter(function() { $(this).animate({ backgroundPositionY : "-=15px" }, 200 ); }); $(".icon").mouseleave(function() { $(this).animate({ backgroundPositionY : "+=15px" }, 200 ); }); });
($(this).index()+1)
获取悬停图标的索引并添加一个,因为.index()
将从零开始,我们希望从一开始。.index()
根据元素的同级元素(恰好是其他按钮)获取元素的索引。我还发布了一个更新,解释了如何更好地将现有函数用作事件处理程序。
$(document).ready(function() {
$(".icon").mouseenter(function() {
$(this).animate({ backgroundPositionY : "-=15px" }, 200 );
});
$(".icon").mouseleave(function() {
$(this).animate({ backgroundPositionY : "+=15px" }, 200 );
});
});