在JavaScript中使用伪元素::before
在JavaScript中使用伪元素::before
如何用JavaScript改变CSS属性::before
?
我的CSS代码如下:
#all-address::before { content: ''; height: 20px; background: linear-gradient(to bottom, transparent 0%, white 45%, white 100%); z-index: 3; display: none; }
现在我想通过JavaScript将display: none
改为display: block
。
我尝试了以下代码,但似乎不起作用:
var div = document.getElementById("all-address"); div.pseudoStyle("before", "display", "block");
尝试以下代码:
window.getComputedStyle( document.querySelector('#all-address'), ':before' ).display='block';
当使用此代码时,Chrome会报错Uncaught NoModificationAllowedError: Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'display' property is read-only
。
将会抛出错误:Uncaught DOMException: Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'display' property is read-only.
尝试新版本(使用属性而不是方法)。
使用伪元素::before在JavaScript中的问题出现的原因是,无法直接从JavaScript中访问伪元素::before或::after,因为它们不是DOM的一部分。但是,仍然可以通过使用CSS类来实现目标。
解决方法是通过在JavaScript中添加类名来改变元素的样式。在上面的示例中,通过使用document.getElementById('abc').className += "minus";
将"minus"类名添加到id为"abc"的元素上。
然后,在CSS中定义了两个样式规则。首先,#all-address:before
的样式规则将::before
伪元素的display
属性设置为none
,使其隐藏起来。然后,#all-address.minus:before
的样式规则将::before
伪元素的display
属性设置为block
,使其显示出来。
通过在JavaScript中添加类名,可以改变元素的类名,从而触发CSS规则的变化,达到改变伪元素样式的目的。
需要注意的是,在代码中添加了一个错误的字符“+”在<script>
标签中,应该将其删除。
希望这能帮助你解决问题。