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

Carles Alcoleamulllhausen提出了一个问题:pure javascript to check if something has hover (without setting on mouseover/out),或许与您遇到的问题类似。

回答者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;};
   }
})();

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:How to JSON stringify a javascript Date and preserve timezone
下一篇:Good way to combine React and Leaflet

相关推荐

官方社区

扫码加入 JavaScript 社区