我现在可能很累并且想法很奇怪,但我根本找不到如何检索元素的聚焦、悬停或访问状态中定义的 CSS 属性的值。目标是使用 Javascript 中的值。
重要:我不需要获取聚焦/悬停/访问的元素。我想使用为以下状态定义的 CSS 属性来访问 DOM 中任何元素的某些值::focus
、:hover
和 :访问过
。
这些伪类在这种情况下似乎没有帮助,所以我是否需要触发相应的状态才能访问这些值?
它应该比这更简单......或者不是吗?
P.S.:用纯 Javascript 或 jQuery 回答即可。
最佳答案
是的,您可以通过阅读样式表来实现这一点。 您可以通过使用 document.styleSheets 来获取它;下面是示例和 jsfiddle 链接。
For security reasons, Opera and Mozilla will not allow you to access the cssRules collection of a stylesheet from another domain or protocol. Attempting to access it will throw a security violation error
function getStyleBySelector( selector )
{
var sheetList = document.styleSheets;
var ruleList;
var i, j;
/* look through stylesheets in reverse order that
they appear in the document */
for (i=sheetList.length-1; i >= 0; i--)
{
ruleList = sheetList[i].cssRules;
for (j=0; j<ruleList.length; j++)
{
if (ruleList[j].type == CSSRule.STYLE_RULE &&
ruleList[j].selectorText == selector)
{
return ruleList[j].style;
}
}
}
return null;
}
console.log(getStyleBySelector('a:hover').color);
console.log(getStyleBySelector('#link:hover').color);
关于javascript - 如何通过 Javascript 访问元素的 focus/hover/visited CSS 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871372/