纯 javascript 检查是否有悬停(不设置鼠标悬停/移出)

2022-01-22 00:00:00 hover jquery javascript

我见过这个 jQuery 语法:

I have seen this jQuery syntax:

if($(element).is(':hover')) { do something}

由于我没有使用 jQuery,我正在寻找用纯 javascript 执行此操作的最佳方法.

Since I am not using jQuery, I am looking for the best way to do this in pure javascript.

我知道我可以保留一个全局变量并使用 mouseovermouseout 设置/取消设置它,但我想知道是否有某种方法可以检查元素的本机而是通过 DOM 属性?也许是这样的:

I know I could keep a global variable and set/unset it using mouseover and mouseout, but I'm wondering if there is some way to inspect the element's native properties via the DOM instead? Maybe something like this:

if(element.style.className.hovered === true) {do something}

另外,它必须是跨浏览器兼容的.

Also, it must be cross browser compatible.

推荐答案

简单地使用 element.matches(':hover') 对我来说似乎效果很好,你可以使用一个综合的 polyfill浏览器也是:https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

Simply using element.matches(':hover') seems to work well for me, you can use a comprehensive polyfill for older browsers too: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

相关文章