javascript - 为什么 Firefox 在页面加载时触发 mouseenter 事件?

标签 javascript google-chrome firefox dom-events

将鼠标悬停在元素上然后刷新页面(不移动鼠标)时:

  • 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 上检查它们。 .

引用this hilarious answer :

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/

相关文章:

css - :hover doesn't work in Firefox

css - Firefox 默认页面内容最小宽度?

javascript - 使用 <img> 为 markdown gatsbyjs 创建自定义组件

javascript - 单击单选按钮时显示弹出窗口

javascript - JQuery 是 (":focus")

firefox - 哪个浏览器更容易开发插件? Chrome 还是火狐浏览器?

css - 打印具有线性渐变和边框的 CSS 对象时,线性渐变背景消失

javascript - 如何在不破坏我的网页的情况下向我的 div 添加滚动条

css - 使用 CSS,Google Chrome 可以创建类似于 24 位 PNG 的 alpha channel 效果吗?

css - Firefox 上的字体问题