首页 > 解决方案 > Javascript 如何在 :active 伪元素上使用 getComputedStyle?

问题描述

我曾尝试将 getComputedStyle 与其他伪元素一起使用,它们都有效。但是当我尝试获取 :active 的属性时,它总是读取默认值。

function myFunction() {
  var elem = document.getElementById("test");
  var theCSSprop = window.getComputedStyle(elem, ":active").getPropertyValue("font-size");
  document.getElementById("demo").innerHTML = theCSSprop;
}
div {
  cursor: pointer
}

div:active {
  font-size: 50pt;
}
<div id="test" style="height: 50px;background-color: yellow;">Test Div</div>
<p><button onclick="myFunction()">Show :active font-size</button></p>
<p>The computed font size for div:active in the test div is: <span id="demo"></span></p>

有没有办法做到这一点?

标签: javascripthtmlcssdom

解决方案


按照规范 getComputedStyle 只接受伪元素作为第二个参数。 https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

但是, :active 不是伪元素,而是伪类。

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements


推荐阅读