pure javascript to check if something has hover (without setting on mouseover/out)(纯 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.
我知道我可以保留一个全局变量并使用 mouseover
和 mouseout
设置/取消设置它,但我想知道是否有某种方法可以检查元素的本机而是通过 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 检查是否有悬停(不设置鼠标悬停/移出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:纯 javascript 检查是否有悬停(不设置鼠标悬停/移出)
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06