Hover/mouseenter事件触发jqueryui';s';制作动画';重复地
因此,我有一个导航,我使用jQuery的UI动画使列表项滑出视图,更改颜色,然后滑回,以不同的颜色显示按钮 我遇到的问题是,每当我将鼠标悬停在列表项上时,就会不断触发悬停事件,直到鼠标离开 更奇怪的是,mouseleave事件似乎在hover事件之后立即触发,而不管鼠标是否实际离开了列表项。无论我是使用悬停还是鼠标,都会发生这种情况 以下是我所拥有的: HTML: CSS: 如果我非常缓慢地将鼠标移到列表中的一个项目中,只需几个像素,我就可以达到我想要的效果。这项任务似乎应该相对容易,让我抓狂 我已经搜索过网络,并尝试过一些方法,比如解除mouseenter事件的绑定,仅在mouseleave事件触发后使用条件来运行动画,但没有效果 任何建议都将不胜感激,最好是在我秃顶之前。Hover/mouseenter事件触发jqueryui';s';制作动画';重复地,jquery,jquery-ui,navigation,hover,mouseenter,Jquery,Jquery Ui,Navigation,Hover,Mouseenter,因此,我有一个导航,我使用jQuery的UI动画使列表项滑出视图,更改颜色,然后滑回,以不同的颜色显示按钮 我遇到的问题是,每当我将鼠标悬停在列表项上时,就会不断触发悬停事件,直到鼠标离开 更奇怪的是,mouseleave事件似乎在hover事件之后立即触发,而不管鼠标是否实际离开了列表项。无论我是使用悬停还是鼠标,都会发生这种情况 以下是我所拥有的: HTML: CSS: 如果我非常缓慢地将鼠标移到列表中的一个项目中,只需几个像素,我就可以达到我想要的效果。这项任务似乎应该相对容易,让我抓狂
谢谢 尝试将您的
li
设置为位置:相对代码>
我只是“粘贴”您的代码并设置相对您的
结果有点滑稽
请参见此处:出现问题的原因是您正在移动元素,因此它不再位于鼠标下方。因此,显然会触发mouseleave()
。您可以通过在a
标记悬停时触发动画来避免这种情况,但使用动画将li
作为目标。见:
以下是您的新js:
$("nav a").mouseenter(function(){
var $li = $(this).find('li');
$li.stop(true,true).animate({bottom:"-50px"},"fast",
function(){
$li.css({'background':'orange','color':'#fff'});
});
$li.stop(true,true).animate({bottom:"-0px"},"fast");
}).mouseleave(function(){
var $li = $(this).find('li');
$li.stop(true,true).animate({bottom:"-50px"},"fast",
function(){
$li.css({'background':'white','color':'#333'});
});
$li.animate({bottom:"-0px"},"fast");
});
您可能已经注意到,在动画完成后激发的回调函数已经过一些优化。您可以通过以下方式传递多个CSS属性:.CSS({'prop1':'val1','prop2':val2'})
此外,我已经优化了代码,因此您不会生成很多jQuery对象,因为这很慢。(注意var$li
行。)谢谢您的建议!虽然导航li已设置为相对。我将把当前CSS添加到我的edit.Nope中。看看这个演示。这个演示确实很奇怪。这里是一些额外的样式:。我的主要问题是,无论鼠标是否离开按钮,都会触发悬停事件,因此如果鼠标移动,按钮会不断上下移动。太棒了!非常感谢你。另外,感谢您优化了这些代码(总是很好地学习最佳实践)。先生,你让我高兴极了!
$("nav li").mouseenter(function(){
$(this).animate({bottom:"-50px"},"fast", function(){$(this).css('background','orange');$(this).css('color','#fff');});
$(this).animate({bottom:"-0px"},"fast");
}).mouseleave(function(){
$(this).animate({bottom:"-50px"},"fast", function(){$(this).css('background','white');$(this).css('color','#333');});
$(this).animate({bottom:"-0px"},"fast");
});
nav{
float:right;
margin-top:91px;
}
nav ul, nav ul li{
display:inline;
}
nav li{
margin-left:10px;
position:relative;
padding:5px 20px;
color:#A29874;
background-color:#fff;
border-top-right-radius:5px;
border-top-left-radius:5px;
}
nav a{
position:relative;
text-decoration:none;
}
$("nav a").mouseenter(function(){
var $li = $(this).find('li');
$li.stop(true,true).animate({bottom:"-50px"},"fast",
function(){
$li.css({'background':'orange','color':'#fff'});
});
$li.stop(true,true).animate({bottom:"-0px"},"fast");
}).mouseleave(function(){
var $li = $(this).find('li');
$li.stop(true,true).animate({bottom:"-50px"},"fast",
function(){
$li.css({'background':'white','color':'#333'});
});
$li.animate({bottom:"-0px"},"fast");
});