jQuery mouseenter、mouseleave 和append 的奇怪组合
在将 jQuery 的 mouseenter
和 mouseleave
事件与对 append
的调用相结合时,我遇到了一个有趣的问题。我的目标是当鼠标进入某些内容时显示额外的内容,然后在鼠标离开时删除它。这与将鼠标悬停在 StackExchange 上的标签上时发生的情况非常相似。顺序是:
- 在
mouseenter
中,创建内容并通过.offset
和.append
将其定位在鼠标下方的元素上。 - 在
mouseleave
中,从屏幕上删除该内容。
我正在操作的元素是 img
,我使用的是 jQuery 1.6.2。问题在于 .append
以某种方式触发了 mouseleave
,而 .mouseenter
很快就会紧随其后,如此循环往复。它在添加的内容上显示出奇怪的闪烁效果,因为它被反复删除和重新添加。请参阅此处关于 jsFiddle 的示例。为什么会发生这种情况?我该如何解决?
编辑:弄清楚了。噢。添加的内容出现在鼠标下方。
I've got an interesting issue with combining jQuery's mouseenter
and mouseleave
events with a call to append
. My object is to show extra content when the mouse enters something and then remove it when the mouse leaves. It's very similar to what happens when you mouse over a tag here on StackExchange. The sequence is:
- In
mouseenter
, create content and position it by the element under the mouse via.offset
and.append
. - In
mouseleave
, remove that content from the screen.
The element I'm operating on is an img
, and I'm using jQuery 1.6.2. The problem is that .append
somehow triggers mouseleave
, which is quickly followed by .mouseenter
, ad infinitum. It appears as a strange flickering effect on the content being added, as it's removed and re-added repeatedly. See an example here on jsFiddle. Why is this happening, and how do I resolve it?
EDIT: figured it out. D'oh. The added content was appearing under the mouse.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况的原因是您在鼠标所在的位置添加了内容。新内容不是原始元素的一部分,因此根据定义,当您显示新 DIV 时,鼠标不再位于 IMG 上。
解决此问题的一种方法是使用图像作为父 DIV 的背景,然后将新 DIV 附加到父 DIV,以便新 DIV 成为父 DIV 的子项。
顺便说一句,您选择不使用 .hover() 是否有原因?
这是一个有效的 jsfiddle 来说明我如何做到这一点。
HTML:
Javascript/Jquery:
CSS:
The reason this happens is that you're adding content where your mouse is. That new content is not part of your original element so by definition when you show the new DIV your mouse is not over the IMG any more.
One way to solve this would be to use the image as a background of a parent DIV and then append the new DIV to the parent so that the new DIV is a child of the parent.
On a side note is there a reason you chose not to use .hover()?
Here's a working jsfiddle for how I'd do this.
HTML:
Javascript/Jquery:
CSS: