选择和操作CSS伪元素,如:: before和:: after使用jQuery
问题描述:
有任何方法来选择/操纵CSS伪元素,例如 :: before
和 :: after
(和一个分号的旧版本)使用jQuery?
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' }
如何使用jQuery将'foo'改为'bar'?
How can I change 'foo' to 'bar' using 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';
}