纯 javascript 检查是否有悬停(不设置鼠标悬停/移出) [英] pure javascript to check if something has hover (without setting on mouseover/out)

查看:22
本文介绍了纯 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

这篇关于纯 javascript 检查是否有悬停(不设置鼠标悬停/移出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆