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

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

问题描述:

有什么方法可以选择/操作 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' }

如何使用 vanilla 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 中:

In 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 中:

In 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';
}