首页 > 解决方案 > 文档上的 mouseenter 和 mouseleave 事件侦听器在 Firefox 中不起作用

问题描述

以下代码在 Chrome 中正常工作,但在 Firefox 中不正常。在 Chrome 中,当我在浏览器内外移动鼠标时,控制台中会有一些输出,但在 Firefox 中并非如此。我的 Firefox 版本是 85.0.2。任何帮助,将不胜感激。

document.addEventListener("mouseenter", () => {
  console.log("mouseenter");
});
document.addEventListener("mouseleave", () => {
  console.log("mouseleave");
});
html,
body {
  width: 100vw;
  height: 100vh;
  background-color: red;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
  </body>
</html>

标签: javascript

解决方案


尝试为页面提供尺寸并改用正文

document.querySelector("body").addEventListener("mouseenter", () => {
  console.log("mouseenter");
});
document.querySelector("body").addEventListener("mouseleave", () => {
  console.log("mouseleave");
});
html, body { width: 100vw; height:100vh; background-color:red; }

事件监听器的测试

const addEventListener = EventTarget.prototype.addEventListener;

EventTarget.prototype.addEventListener = function(name, handler) {
  addEventListener.call(this, name, function(event) {
    window.event = event;

    handler(event);
  })
};

function showEvent(e) {
  // just demonstrating that window.event is set
  console.log(e.type);
}


document.addEventListener('mouseenter', showEvent);
document.addEventListener('mouseleave', showEvent);
document.addEventListener('mouseover', showEvent);
document.addEventListener('mouseout', showEvent);
html,
body {
  width: 100vw;
  height: 100vh;
  background-color: red;
}
https://stackoverflow.com/questions/47786133/workaround-for-firefoxs-lack-of-window-event


推荐阅读