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

查看:60
本文介绍了使用javascript(或jQuery)选择和操作CSS伪元素,例如:: before和:: after的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jQuery选择/操作CSS伪元素,例如::before::after(以及带有分号的旧版本)?

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

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

$('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';
}

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

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