有什么方法可以使用jQuery选择/操作CSS伪元素,例如::before::after(以及带有一个分号的旧版本)吗?

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

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


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

最佳答案

您还可以将内容传递给具有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';
}

关于javascript - 使用jQuery选择和操作CSS伪元素,例如:: before和:: after,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28675295/

10-11 22:15
查看更多