当鼠标已经位于 onLoad 元素上方时,带有 .toggle() 的 jQuery MouseEnter 和 MouseOut 事件会反转?
我有一个下拉菜单,可以很好地使用以下代码:
$('#menu ul li').mouseenter(function(){
$(this).children(".dropdown").toggle();
}).mouseleave(function(){
$(this).children(".dropdown").toggle();
});
这正如您所期望的那样。问题是,如果当 $(document).ready(function() 时,鼠标已经在
被触发,切换会以相反的方式工作吗?$('#menu ul li')
上 mouseenter
{ })
我怎样才能避免这种情况?
I have a dropdown menu working great with the following code:
$('#menu ul li').mouseenter(function(){
$(this).children(".dropdown").toggle();
}).mouseleave(function(){
$(this).children(".dropdown").toggle();
});
This works as you would expect. The issue is that if the mouse is already mouseenter
on the $('#menu ul li')
when the $(document).ready(function(){ })
is fired, the toggle works the other way round?
How can I avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不想在
mouseenter
上执行show()
并在mouseleave
上执行hide()
吗?don't you want to do
show()
onmouseenter
andhide()
onmouseleave
?您的鼠标事件处理程序可以传入显式布尔
showOrHide
值,而不是仅调用不带参数的toggle
。将true
传递给mouseenter
例程中的toggle()
,并在mouseleave
中传递false
。或者按照其他答案的建议进行操作,只需使用show
和hide
即可。Instead of just calling
toggle
with no arguments, your mouse event handlers can pass in explicit booleanshowOrHide
values. Passtrue
totoggle()
in themouseenter
routine, andfalse
inmouseleave
. Or do as suggested by the other answer and just useshow
andhide
.当您在不移动鼠标的情况下加载文档时,在移动鼠标之前不会切换鼠标悬停操作。但我认为鼠标悬停会随着鼠标移动而切换,如果它已经在 onLoad“上方”,则发生事件。
这段代码怎么样?
不管怎样,我认为你的错误来自于 mouseout 没有被切换,因为 JS 只检查每 x 毫秒,如果你移动得太快,它就会在不调用事件的情况下离开 div。
如果您不关心动画,那么使用 CSS 执行此操作始终比使用 JS 更好。
你需要像这样设置它:
CSS:
When you load the document without moving the mouse, no mouseover action will be toggled until you move the mouse. But i think mouseover is toggled as your mouse moves, event if it's already "over" onLoad.
What about this code ?
Anyways, i think your bug comes from mouseout not being toggled because JS only checks every x ms, and if you move too fast, it gets out of the div without calling the event.
If you don't care about animations, doing this with CSS is always a better way then with JS.
You'll need to set it up like this :
CSS: