将鼠标悬停在元素上然后刷新页面(不移动鼠标)时:
- Chrome 不会在页面加载时触发 mouseenter 事件
- Firefox 确实在页面加载时触发 mouseenter 事件
下面是一个示例片段。要重现该问题,请将鼠标悬停在 div
上,然后刷新页面。在 Chrome 中,div
不包含“mouseenter”。在 Firefox 中,确实如此。
请注意,这在 Stacksnippets 环境中不起作用,因为您需要先单击“运行片段”。 JSFiddle:https://jsfiddle.net/9fu6cx5d/7/
let div = document.getElementById('my-div');
div.addEventListener('mouseenter', function () {
div.innerHTML = 'mouseenter';
});
#my-div {
width: 150px;
height: 150px;
background-color: #aaaaaa;
}
<div id="my-div">
</div>
哪种浏览器具有正确的行为?我如何解决行为差异或至少使它们的行为相同?
Chrome 版本:59.0.3071.115(官方版本)(64 位)
Firefox 版本:54.0(64 位)
最佳答案
正如评论中所指出的,根据规范,Chrome 的行为是正确的。以下是有关如何解决差异的想法。
您可以通过在文档加载时检查鼠标是否位于 div 的边界内来确保获得正确的值。不幸的是,JS 中无法在不触发事件的情况下检查鼠标位置,因此您将不得不诉诸一些涉及 CSS 悬停规则的 hack,并在 $(document).ready
上检查它们。 .
Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.
N.B. DON'T DO THIS.
虽然您绝对不应该这样做,但如果您只需要解决浏览器的怪癖,那么使用无效的悬停样式来检查元素是否悬停而不需要 JS 事件的一般想法是一个不错的选择。我正在使用font-weight
在下面的示例中,但您可以将其更改为适合您的任何内容。
CSS
#my-div:hover {font-weight:700;}
js
// Pseudocode!
var mouseIsInside = false,
div = $('#my-div');
$(document).ready(function(){
if (div.css('font-weight') === 700) {
mouseIsInside = true;
}
doStuffIfMouseInside();
});
div.on('mouseenter', function(){
mouseIsInside = true;
doStuffIfMouseInside();
})
function doStuffIfMouseInside() {
if (mouseIsInside) {
...
}
}
关于javascript - 为什么 Firefox 在页面加载时触发 mouseenter 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45034536/