我做了一个覆盖页面上某些元素的 :hover 的函数。它在正常和 :hover 效果之间逐渐消失。那是因为我必须在我的 CSS 文件中创建一个 .hover 类。我觉得这有点不干净。我如何阅读 :hover 伪类内容?
阅读:使用 javascript 悬停伪类
IT技术
javascript
jquery
css
2021-02-25 21:21:25
5个回答
getComputedStyle
在接受的答案上使用as 将不起作用,因为:
- 悬停状态的计算样式仅在元素实际处于该状态时可用。
- 第二个参数 to
getComputedStyle
应该是空的或伪元素。它不起作用,:hover
因为它是一个伪类。
这是一个替代解决方案:
function getCssPropertyForRule(rule, prop) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if(rules[j].selectorText == rule) {
return rules[j].style[prop];
}
}
}
}
// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));
您可以访问document.styleSheets
并查找应用于该特定元素的规则。但这并不比使用简单的附加类更干净。
更新:我不知何故弄错了。下面的例子不起作用。有关解释,请参阅@bfavaretto 的评论。
在 Firefox、Opera 和 Chrome 或任何其他浏览器中正确实现window.getComputedStyle
是非常简单的。您只需将“悬停”作为第二个参数传递:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
display: block;
width: 200px;
height: 200px;
background: red;
}
div:hover {
background: green;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementsByTagName("div")[0];
var style = window.getComputedStyle(div, "hover");
alert(style.backgroundColor);
};
</script>
</body>
</html>
但我不相信 Internet Explorer 还没有解决方案,除非因此,到目前为止,document.styleSheets
按照 Gumbo 的建议使用。但是会有差异。.hover
上课是最好的解决方案。一点也不脏。
如果这里有人使用已接受的问题的答案但它不起作用,那么这里有一个很好的功能,可能:
function getPseudoStyle(id, style) {
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var targetrule = "";
if (all[i].id === id) {
if(all[i].selectorText.toLowerCase()== id + ":" + style) { //example. find "a:hover" rule
targetrule=myrules[i]
}
}
return targetrule;
}
}
有一种:hover
使用 javascript获取伪类的替代方法。您可以hover
在content
属性中编写伪类的样式。
p::before,
p::after{
content: 'background-color: blue; color:blue; font-size: 14px;';
}
然后通过getComputedStyle()方法读取它:
console.log(getComputedStyle(document.querySelector('p'),':before').getPropertyValue('content'));