根据 documentation,函数 window.getComputedStyle
应该能够获取伪类的计算样式,如 :hover .
它也在 another question 中作为答案进行了解释
但正如该问题中最后一条评论所说,实际上它根本不起作用,它只是返回正常样式,而不是 :hover 样式。您可以在 this jsfiddle 中亲自查看.警报返回红色,而不是绿色。
documentation on developer.mozilla.org也有一个示例,但这也不起作用 - 请参阅 here .
在this question回答者在评论中说它根本不起作用,但没有给出解释。
会不会是样式表必须在函数返回正确值之前完全呈现?我试过设置一些延迟,但似乎没有任何效果。
我尝试过最新的 Firefox、Chrome 和 IE 浏览器。有人知道为什么这个功能没有按预期工作吗?
最佳答案
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt
是“指定要匹配的伪元素的字符串”。伪元素 类似于::before
或::after
,它们是由CSS 样式生成的元素。 :hover
、:visited
或其他类似效果是伪类。他们不会创建新元素,而是将专门的类样式应用于元素。
不可能获得伪类的计算样式,至少不能使用 getComputedStyle
。但是,您可以遍历 CSS 规则并尝试找到合适的选择器,但我不建议您这样做,因为某些浏览器不遵循 DOM-Level-2-Style 规则,您必须检查哪个规则将影响您的特定元素:
/* Style */
p a:hover{ color:yellow; background:black;}
p > a:hover{ color:green; background:white;}
p > a+a:hover{ color:fuchsia; background:blue;}
// JS
var i,j, sel = /a:hover/;
for(i = 0; i < document.styleSheets.length; ++i){
for(j = 0; j < document.styleSheets[i].cssRules.length; ++j){
if(sel.test(document.styleSheets[i].cssRules[j].selectorText)){
console.log(
document.styleSheets[i].cssRules[j].selectorText,
document.styleSheets[i].cssRules[j].style.cssText
);
}
}
}
Result: p a:hover color: yellow; background: none repeat scroll 0% 0% black; p > a:hover color: green; background: none repeat scroll 0% 0% white; p > a + a:hover color: fuchsia; background: none repeat scroll 0% 0% blue;
另见:
关于javascript - 为什么 getComputedStyle 不能使用像 :hover? 这样的伪类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495535/