在大多数(所有?)浏览器中,如果浏览器在鼠标下呈现带有mouseEnter / mouseOver侦听器的元素,则不会触发该事件。所以我们现在将鼠标悬停在一个元素上,而代码并不像鼠标在元素上一样。
对此有一个简单的解决方法吗?
答案 0 :(得分:1)
您可以使用MutationObserver
监视所有HTML节点,以查找可能会将页面上的元素移动到光标下的更改。如果发生任何此类更改,您可以使用Document.elementFromPoint
查找悬停元素,然后使用manually trigger该元素上的mouseover
事件:
function dispatchArtificialMouseover() {
const elementMouseIsOver = document.elementFromPoint(
event.clientX,
event.clientY
);
const mouseoverEvent = new MouseEvent("mouseover");
elementMouseIsOver.dispatchEvent(mouseoverEvent);
}
const observerConfig = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
const observer = new MutationObserver(dispatchArtificialMouseover);
const rootElement = document.body;
observer.observe(rootElement, observerConfig);
但是,我猜想,如果经常发生任何变化,那么收听页面上的所有更改都会降低页面速度,例如当用户在输入中键入文本时。