简体   繁体   English

鼠标悬停和鼠标移出事件会不匹配吗?

[英]Can mouseover and mouseout events be mismatched?

I'm trying to track if mouse is within my HTML element or not (note: it also has child elements). 我试图跟踪鼠标是否在HTML元素内(请注意:它也有子元素)。 The trivial solution (which I'm employing right now) is to attach to mouseover / mouseout and count them - if there are more " mouseovers " than " mouseouts ", then the mouse should be within. 最简单的解决方案(我现在正在使用)是附加到mouseover / mouseout并计数它们-如果“ mouseovers ”多于“ mouseouts ”,则鼠标应该在其中。

But I wonder - can this fail? 但我想知道-这会失败吗? Can either of these events be "skipped" under some (more or less bizarre) circumstances, leaving me with a mismatched count? 在某些(或多或少奇怪的)情况下,这些事件中的任何一个都可以被“跳过”,而使我的计数不匹配吗?

A few simple trials didn't yield any such situations, but then there are a lot of edge cases and I can't possibly think of them all. 一些简单的试验并没有得出任何这样的情况,但是随后有很多边缘情况,我想不出来。 Has anyone ever come across such a situation? 有没有人遇到过这种情况?

Clarification: I have not come across such a problem. 澄清:我还没有遇到过这样的问题。 I'm wondering if such a problem is possible or not. 我想知道是否可能出现这样的问题。

Added: A case just came to my mind - a mouseover / mouseout on a child element which is prevented from bubbling in its handler. 补充:我想到了一个案例-子元素上的mouseover / mouseout被阻止在其处理程序中冒泡。 Not the case for my code, but a possibility still. 我的代码不是这种情况,但仍有可能。

I have had similar things happen.. driving me crazy. 我曾经发生过类似的事情。 I came to the assumption/conclusion that, at least in my case, it may have had something to do with event bubbling. 我得出的假设/结论是,至少就我而言,这可能与事件冒泡有关。 Are you using jquery? 您在使用jQuery吗? It may be worth while to step though the uncompressed libraries.. if you really need the guarantee. 如果您确实需要保证,那么值得尝试未压缩的库。 Otherwise, if your code is flexible enough, you could work around it..which is what I did. 否则,如果您的代码足够灵活,则可以解决该问题。这就是我所做的。

Bubbling is very likely the source of the problem. 冒泡很可能是问题的根源。 You get a mouseout event when the mouse moves into an inner element. 当鼠标移入内部元素时,您将获得一个mouseout事件。 http://www.quirksmode.org/dom/events/mouseover.html http://www.quirksmode.org/dom/events/mouseover.html

Suggestion, use a library. 建议,使用图书馆。 They abstract cross browser differences between the mouseenter and mouseleave events which do not bubble. 它们抽象了mouseenter和mouseleave事件之间不会冒泡的跨浏览器差异。 http://api.jquery.com/mouseenter/ http://api.jquery.com/mouseenter/

If you don't want to use a library, you need to check yourself if the mouse is within the div you're tracking before you fix the counter. 如果您不想使用库,则需要先检查一下鼠标是否在要跟踪的div内,然后再固定计数器。 If you show the code you have, it's easier to show you how to fix it. 如果显示您拥有的代码,则更容易向您显示如何对其进行修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM