使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如 ::before 和 ::after [英] Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

查看:57
本文介绍了使用 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';
}

这篇关于使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如 ::before 和 ::after的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆