This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

(22个答案)


1年前关闭。




这是我的代码如下所示:
$('.mainSpan:before').css('background','url(_gfx/cmn/main_bg.png)');

这似乎不起作用,所以我问是否有可能添加
jQuery将背景图像阴影元素。

最佳答案

无法使用Javascript直接访问伪元素,因为它们不是DOM的一部分。您可以使用which most, although not all, browsers in current use support中的第二个可选参数 .getComputedStyle() 来读取其样式,但不能直接更改其样式。

但是,您可以通过添加包含新规则的新style元素来间接更改其样式。例如:

http://jsfiddle.net/sjFML/

初始CSS为:before伪元素分配了绿色背景,通过插入新的style元素将其变为黑色。

HTML:

<div id="theDiv"></div>

CSS:
#theDiv {
    height: 100px;
    background: red;
}

#theDiv:before {
    content:' ';
    display: block;
    width: 50px;
    height: 50px;
    background: green;
}

Javascript:
var styleElem = document.head.appendChild(document.createElement("style"));

styleElem.innerHTML = "#theDiv:before {background: black;}";

关于javascript - 更改:before and :after pseudo-elements?的样式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21032481/

10-09 18:21
查看更多