小编典典

使用jQuery选择和操作CSS伪元素,例如:: before和:: after

javascript

有没有办法使用jQuery 选择/处理CSS伪元素,例如::before::after(以及带有分号的旧版本)?

例如,我的样式表具有以下规则:

.span::after{ content:'foo' }

如何使用jQuery将’foo’更改为’bar’?


阅读 1537

收藏
2020-04-22

共1个答案

小编典典

您还可以将内容传递给具有data属性的伪元素,然后使用jQuery进行操作:

在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的解决方案结合使用,如下所示:

在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';
}
2020-04-22