鼠标悬停/离开问题
我有一个 span
,其中包含一个锚点和一个 span
。下面的示例
<span id="x"><a id="a_in" href="">link</a><span id="x_in">x</span></span>
现在我在带有 id="x"
的 span
上附加一个 mouseenter
/ mouseleave
事件。当我将鼠标悬停在 span id="x"
上时,它会触发 mouseenter
/ mouseleave
,这很好。问题是当我mouseover
时,父span
mouseleave内的span id="x_1"
被触发。
我希望仅当我 mouseenter
或 mouseleave
父级时才触发 mouseenter
/ mouseleave
。
有什么想法如何避免这种情况吗?
I have a span
that includes an anchor and a span
. Example below
<span id="x"><a id="a_in" href="">link</a><span id="x_in">x</span></span>
Now I am attaching a mousenter
/ mouseleave
event on the span
with id="x"
. When I mouse over the the span id="x"
it triggers the mousenter
/ mouseleave
that's fine. The problem is when I mouseover
the span id="x_1"
inside the parent span
mouseleave gets triggered.
I want mousenter
/ mouseleave
to be triggered only when I mouseenter
or mouseleave
the parent.
Any ideas how to avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短回答:你无法避免这一点,
但你可以确定 mouseleave/enter 只发生在父级上
short answer: you can't avoid this,
but you can determine that the mouseleave/enter only happens on the parent
只需具体说明您想要在什么事件上触发什么元素即可。如果您使用 jQuery:
$("span#x").hover(function() {
//鼠标输入的动作逻辑
}, 功能() {
//鼠标离开的动作逻辑
});
Just be specific in what event you want to fire on what element. If your using jQuery:
$("span#x").hover(function() {
//action logic for mouse enter
}, function() {
//action logic for mouse leave
});
您需要
cancelBubble()
和stopPropagation()
。请参阅此处:http://www. thedutchguy.com/article/javascript-prevent-event-bubbling-parent-child-when-fired.html
以及此处:
you need
cancelBubble()
andstopPropagation()
.See here: http://www.thedutchguy.com/article/javascript-prevent-event-bubbling-parent-child-when-fired.html
and also here: http://www.openjs.com/articles/prevent_default_action/
好的……谢谢你们。问题出在我在 mouseenter 上显示的一个新 div 上,它与我的 SPAN X 重叠并触发了 mouseleave。
还...
...所以它几乎按照你们的建议做了,而且效果很好。
http://demos.mootools.net/Mouseenter
以防万一有人正在寻找如何停止传播mootools...
$('myelement').addEvent('click', function (e) {
var 事件 = e ||窗口.事件;
if (event.stopPropagation) {
event.stopPropagation();
} 别的 {
event.cancelBubble = true;
}
});
感谢您的帮助!
OK...thank you guys. The prob was on a new div that I was showing on the mouseenter which overlapped my SPAN X and triggered mouseleave.
Also...
...so pretty much it does what you guys are suggesting and it works fine.
http://demos.mootools.net/Mouseenter
Just in case someone is looking for how to stop propagation using mootools...
$('myelement').addEvent('click', function (e) {
var event = e || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
});
Thank you for your help!