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

标签 javascript jquery css jquery-selectors pseudo-element

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

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

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

如何使用 vanilla JS 或 jQuery 将“foo”更改为“bar”?

最佳答案

您还可以将内容传递给具有数据属性的伪元素,然后使用 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 - 使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如::before 和::after,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40352139/

相关文章:

background - CSS背景图片和默认背景?

javascript - 查询 sequelize 中的关联位置?

javascript - 在 JS Connect-Four 中返回获胜的单元格坐标

javascript - ajax调用数据过多会导致页面未找到错误吗?

javascript - 如果被拒绝,再次请求地理定位许可

javascript - 悬停时 undefined variable

jquery - 如何改变 DIV 行的背景颜色? (Jquery 和/或 CSS)

jquery - 元素淡入淡出不完全

javascript - html 格式的电子邮件内容

javascript - AngularJS 中嵌套复选框的编程检查/检查