悬停、鼠标悬停和鼠标移出
我正在学习和使用 jQuery,并且想要显示某些元素的删除图标。
我有一个外部主 div,其中包含许多元素的包装器。在元素包装器内部,我想当用户将鼠标悬停在元素包装器上时显示删除图标,并在用户移出元素包装器时将其删除。
使用 mouseover
和 mouseout
,我可以显示和删除图标,但是一旦我将鼠标移到删除图标上,它就会被删除,因为它会触发 mouseout元素包装器的
事件。我做错了什么?
I'm learning and using jQuery and want to display a delete icon for some elements.
I have an outer main div, which contains number of wrappers for elements. Inside the element wrapper, I want to display a delete icon when the user hovers over the element wrapper, and remove it when user moves out of the element wrapper.
Using mouseover
and mouseout
, I can display and remove the icon, but as soon as I move my mouse over the delete icon it is removed because it fires the mouseout
event for the element wrapper. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个选项供您选择:
:hover
伪类(但前提是您不必支持 IE6)mouseenter
和mouseleave
事件CSS 的
:hover
伪类如果您不需要 IE6 支持,可以通过使用
:hover
伪类:实例
但是,IE6 不支持
:hover
伪类-class,a
元素除外。 IE7+ 和所有最新的其他浏览器都是如此。mouseenter
和mouseleave
事件如果 CSS 不能为您完成此操作,您需要寻找
mouseenter
和mouseleave
> 事件,这些事件是 IE 特定的,但由 jQuery 在所有其他浏览器上模拟。 jQuery 甚至有一个方便的函数,hover
,用于将处理程序连接到两者事件,以便您可以轻松完成您想要做的事情。这是一个完整的实时示例:
HTML:
使用 jQuery 的 JavaScript:
mouseover 遇到问题的原因
和mouseout
是它们冒泡,因此父元素上的mouseout
处理程序会看到冒泡的mouseout
当鼠标移动到删除元素时,从底层元素中删除。mouseenter
和mouseleave
不会冒泡,因此它们不存在这个问题。Two options for you:
:hover
pseudo-class (but only if you don't have to support IE6)mouseenter
andmouseleave
eventsCSS's
:hover
pseudo-classYou can make the browser do all the work if you don't need IE6 support, by using the
:hover
pseudo-class:Live example
However, IE6 doesn't support the
:hover
pseudo-class except ona
elements. IE7+ and all recent other browsers do.mouseenter
andmouseleave
eventsIf CSS doesn't do it for you, you're looking for the
mouseenter
andmouseleave
events, which are IE-specific but emulated by jQuery on all other browsers. jQuery even has a convenient function,hover
, for hooking up handlers to both events so you can readily accomplish what you're looking to do.Here's a complete live example:
HTML:
JavaScript using jQuery:
The reason you had trouble with
mouseover
andmouseout
is that they bubble, and so yourmouseout
handler on your parent element was seeing the bubbledmouseout
from the underlying element when your mouse moved into the delete element.mouseenter
andmouseleave
don't bubble, and so they don't have that problem.您是否尝试过使用
mouseenter
和mouseleave
事件?have you tried using
mouseenter
andmouseleave
events instead?您可以在 jQuery 事件 onmouseover 和 onmouseout 上应用样式。当用户将鼠标悬停在菜单上时,该事件将触发,您可以在那里设置效果。
对于更多详情
You can apply style on the jQuery event onmouseover and onmouseout. When the user hovers over the menu this event will trigger there you can set effects.
for more details