获取伪 类 的值
Get value of pseudo classes
.a:before {
content: 'b';
display: table;
}
如何获取 class 'a' 的内容值?我试过:
`var b = window.getComputedStyle(document.querySelector('a'), ':before').getPropertyValue('content');`
它 return 我出错了:
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
正如其他人指出的那样,您在选择器中 a
之前缺少一个点。正确的代码应该是这样的:
var text = getComputedStyle(document.querySelector('.a'), ':before').getPropertyValue('content');
alert(text);
.a:before {
content: 'b';
display: table;
}
<div class="a"></div>
作为一般的调试策略,最好将较长的语句分成较小的部分,以确定代码中的错误。
例如,在这里您可以将 JavaScript 重写为:
var a = document.querySelector('a');
var computedStyle = window.getComputedStyle(a, ':before');
var content = computedStyle.getPropertyValue('content');
这样,我们立即看到第一个语句中分配的值 a
实际上是 null
,这解释了第二个语句中的 TypeError。
这将问题简化为 document.querySelector('a')
? 中的问题,这更容易处理。
要像这样访问 css 伪 class 的内容 属性:
.a::before {
content: 'b';
display: table;
}
你可以使用这个 javascript:
window.getComputedStyle(document.querySelector('.a'),':before').getPropertyValue('content');
确保css css中的伪class有::
并且querySelector使用了一个点('.a')
这是一个有效的 FIDDLE。
.a:before {
content: 'b';
display: table;
}
如何获取 class 'a' 的内容值?我试过:
`var b = window.getComputedStyle(document.querySelector('a'), ':before').getPropertyValue('content');`
它 return 我出错了:
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
正如其他人指出的那样,您在选择器中 a
之前缺少一个点。正确的代码应该是这样的:
var text = getComputedStyle(document.querySelector('.a'), ':before').getPropertyValue('content');
alert(text);
.a:before {
content: 'b';
display: table;
}
<div class="a"></div>
作为一般的调试策略,最好将较长的语句分成较小的部分,以确定代码中的错误。 例如,在这里您可以将 JavaScript 重写为:
var a = document.querySelector('a');
var computedStyle = window.getComputedStyle(a, ':before');
var content = computedStyle.getPropertyValue('content');
这样,我们立即看到第一个语句中分配的值 a
实际上是 null
,这解释了第二个语句中的 TypeError。
这将问题简化为 document.querySelector('a')
? 中的问题,这更容易处理。
要像这样访问 css 伪 class 的内容 属性:
.a::before {
content: 'b';
display: table;
}
你可以使用这个 javascript:
window.getComputedStyle(document.querySelector('.a'),':before').getPropertyValue('content');
确保css css中的伪class有::
并且querySelector使用了一个点('.a')
这是一个有效的 FIDDLE。