使用javascript(或jQuery)选择和操作CSS伪元素,例如:: before和:: after
是否可以使用jQuery选择/操作CSS伪元素,例如::before
和::after
(以及带有分号的旧版本)?
Is there any way to select/manipulate CSS pseudo-elements such as ::before
and ::after
(and the old version with one semi-colon) using jQuery?
例如,我的样式表具有以下规则:
For example, my stylesheet has the following rule:
.span::after{ content:'foo' }
如何使用香草JS或jQuery将'foo'更改为'bar'?
How can I change 'foo' to 'bar' using vanilla JS or jQuery?
您还可以将内容传递给具有data属性的伪元素,然后使用jQuery进行操作:
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
在HTML中:
<span>foo</span>
在jQuery中:
$('span').hover(function(){
$(this).attr('data-content','bar');
});
在CSS中:
span:after {
content: attr(data-content) ' any other text you may want';
}
如果要防止显示其他文本",可以将其与seucolega的解决方案结合使用,如下所示:
If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:
在HTML中:
<span>foo</span>
在jQuery中:
$('span').hover(function(){
$(this).addClass('change').attr('data-content','bar');
});
在CSS中:
span.change:after {
content: attr(data-content) ' any other text you may want';
}