获取伪类的值

时间:2015-09-29 10:58:16

标签: javascript jquery css pseudo-class

.a:before {
  content: 'b';
  display: table;
      }

如何获得“a”类的内容价值?我试过了:

`var b = window.getComputedStyle(document.querySelector('a'), ':before').getPropertyValue('content');`

它给我一个错误:

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

2 个答案:

答案 0 :(得分:1)

正如其他人所指出的那样,你在选择器a之前错过了一个点。正确的代码应如下所示:



var text = getComputedStyle(document.querySelector('.a'), ':before').getPropertyValue('content');
alert(text);

.a:before {
  content: 'b';
  display: table;
}

<div class="a"></div>
&#13;
&#13;
&#13;

作为一般调试策略,最好将较长的语句拆分成较小的部分,以识别代码中的错误。 例如,在这里您可以将JavaScript重写为:

var a = document.querySelector('a');
var computedStyle = window.getComputedStyle(a, ':before');
var content = computedStyle.getPropertyValue('content');

这样,我们立即看到a(第一个语句中指定的值)实际上是null,这解释了第二个语句中的TypeError。 这可以将问题减少到document.querySelector('a')?中的错误,这相当容易处理。

答案 1 :(得分:1)

要访问css伪类的content属性,请执行以下操作:

.a::before {
  content: 'b';
  display: table;
}

你可以使用这个javascript:

window.getComputedStyle(document.querySelector('.a'),':before').getPropertyValue('content');

确保css中css中的伪类具有::并且querySelector使用a ('.a')

这是一个有效的FIDDLE

相关问题