Javascript 纯javascript来检查是否有悬停(没有设置鼠标悬停/退出)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14795099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:56:56  来源:igfitidea点击:

pure javascript to check if something has hover (without setting on mouseover/out)

javascriptjqueryhover

提问by mulllhausen

I have seen this jQuery syntax:

我见过这个 jQuery 语法:

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

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

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

I know I could keep a global variable and set/unset it using mouseoverand 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:

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

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

Also, it must be cross browser compatible.

此外,它必须是跨浏览器兼容的。

采纳答案by Niet the Dark Absol

First you need to keep track of which elements are being hovered on. Here's one way of doing it:

首先,您需要跟踪悬停在哪些元素上。这是一种方法:

(function() {
    var matchfunc = null, prefixes = ["","ms","moz","webkit","o"], i, m;
    for(i=0; i<prefixes.length; i++) {
        m = prefixes[i]+(prefixes[i] ? "Matches" : "matches");
        if( document.documentElement[m]) {matchfunc = m; break;}
        m += "Selector";
        if( document.documentElement[m]) {matchfunc = m; break;}
    }
    if( matchfunc) window.isHover = function(elem) {return elem[matchfunc](":hover");};
    else {
        window.onmouseover = function(e) {
            e = e || window.event;
            var t = e.srcElement || e.target;
            while(t) {
                t.hovering = true;
                t = t.parentNode;
            }
        };
        window.onmouseout = function(e) {
            e = e || window.event;
            var t = e.srcElement || e.target;
            while(t) {
                t.hovering = false;
                t = t.parentNode;
            }
        };
        window.isHover = function(elem) {return elem.hovering;};
   }
})();

回答by zb'

You can use querySelectorfor IE>=8:

您可以将querySelector用于 IE>=8

const isHover = e => e.parentElement.querySelector(':hover') === e;    

const myDiv = document.getElementById('mydiv');
document.addEventListener('mousemove', function checkHover() {
  const hovered = isHover(myDiv);
  if (hovered !== checkHover.hovered) {
    console.log(hovered ? 'hovered' : 'not hovered');
    checkHover.hovered = hovered;
  }
});
.whyToCheckMe {position: absolute;left: 100px;top: 50px;}
<div id="mydiv">HoverMe
  <div class="whyToCheckMe">Do I need to be checked too?</div>
</div>

to fallback I think it is ok @Kolink answer.

回退我认为可以@Kolink 回答。

回答by Hugheth

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

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

回答by mulllhausen

it occurred to me that one way to check if an element is being hovered over is to set an unused property in css :hoverand then check if that property exists in javascript. its not a proper solution to the problem since it is not making use of a dom-native hover property, but it is the closest and most minimal solution i can think of.

我突然想到,检查元素是否被悬停的一种方法是在 css 中设置一个未使用的属性:hover,然后检查该属性是否存在于 javascript 中。它不是问题的正确解决方案,因为它没有使用 dom-native 悬停属性,但它是我能想到的最接近和最小的解决方案。

<html>
    <head>
        <style type="text/css">
#hover_el
{   
    border: 0px solid blue;
    height: 100px;
    width: 100px;
    background-color: blue;
}   
#hover_el:hover
{   
    border: 0px dashed blue;
}
        </style>
        <script type='text/javascript'>
window.onload = function() {check_for_hover()};
function check_for_hover() {
    var hover_element = document.getElementById('hover_el');
    var hover_status = (getStyle(hover_element, 'border-style') === 'dashed') ? true : false;
    document.getElementById('display').innerHTML = 'you are' + (hover_status ? '' : ' not') + ' hovering';
    setTimeout(check_for_hover, 1000);
};
function getStyle(oElm, strCssRule) {
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle) {
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle) {
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) {
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
};
        </script>
    </head>
    <body>
        <div id='hover_el'>hover here</div>
        <div id='display'></div>
    </body>
</html>

(function getStylethanks to JavaScript get Styles)

(功能getStyle感谢JavaScript get Styles

if anyone can think of a better css property to use as a flag than solid/dashedplease let me know. preferably the property would be one which is rarely used and cannot be inherited.

如果有人能想到一个更好的 css 属性用作标志,solid/dashed请告诉我。该财产最好是很少使用且不能继承的财产。