gpt4 book ai didi

javascript - 为什么 getComputedStyle 不能使用像 :hover? 这样的伪类

转载 作者:行者123 更新时间:2023-11-28 03:42:08 27 4
gpt4 key购买 nike

根据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/44156157/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com