根据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或其他类似效果是pseuodo- 。他们不会创建新元素,而是将专门的类样式应用于该元素。

不可能获得伪类的计算样式,至少不能使用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
            );
        }
    }
}

结果:
p a:悬停颜色:黄色;背景:无重复滚动0%0%黑色;
p> a:悬停颜色:绿色;背景:无重复滚动0%0%白色;
p> a + a:悬停颜色:紫红色;背景:无重复滚动0%0%蓝色;

也可以看看:
  • MDN: getComputedStyle examples
  • W3C:CSS2: 5.10 Pseudo-elements and pseudo-classes
  • SO:Setting CSS pseudo-class rules from JavaScript
  • 10-07 17:40