纯JavaScript检查是否有东西悬停(没有设置鼠标悬停/出) [英] pure javascript to check if something has hover (without setting on mouseover/out)
本文介绍了纯JavaScript检查是否有东西悬停(没有设置鼠标悬停/出)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if($(element).is(':hover')){做一些事情}
由于我没有使用jQuery,我正在寻找最好的方法来做到这一点纯JavaScript。
我知道我可以使用 mouseover
和<$ c设置/取消设置全局变量$ c> mouseout ,但我想知道是否有方法通过DOM检查元素的本地属性?可能是这样的:
if(element.style.className.hovered === true){do something}
此外,它必须是跨浏览器兼容的。
解决方案
首先,您需要跟踪哪些元素被徘徊。这里有一种方法:
(function(){
var matchfunc = null,prefixes = [ (i = 0; i< prefixes.length; i ++){
m = prefixes [i])的ms,moz,webkit,o +(prefixes [i]?Matches:matches);
if(document.documentElement [m]){matchfunc = m; break;}
m + =Selector; $ b $如果(match.dcf)window.isHover = function(elem){return elem [matchfunc](:hover)如果(document.documentElement [m]){matchfunc = m; break;}
}
if );};
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;};
}
})();
I have seen this jQuery syntax:
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.
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.
解决方案
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检查是否有东西悬停(没有设置鼠标悬停/出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文