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

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

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

我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?


当前回答

下面是访问:after和:before样式属性的方法,在css中定义:

// Get the color value of .element:before
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color');

// Get the content value of .element:before
var content = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('content');

其他回答

一种有效但不太有效的方法是在文档中添加带有新内容的规则,并用类引用它。根据需要,类可能需要为内容中的每个值提供唯一的id。

$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');

$ (' .span ')。attr(“data-txt”、“foo”); $ (' .span ')。点击(函数(){ (美元)。Attr ('data-txt',"任何其他文本"); }) .span { } .span:{后 内容:attr (data-txt); } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> < div class =“跨度”> < / div >

如果你想完全通过CSS来操作::before或::after sudo元素,你可以用JS来做。见下文;

jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');

注意<style>元素是如何具有一个ID的,如果样式动态变化,可以使用该ID删除它并再次添加到它。

这样,在JS的帮助下,你的元素就可以完全按照你想要的样式通过CSS进行样式化。

为什么要添加类或属性,当你可以添加一个样式头

$('head').append('<style>.span:after{ content:'changed content' }</style>')

下面的解决方案告诉你如何用javascript的attr属性更新伪元素。

在HTML中添加一个属性,你可以用javascript setAttribute操作它。

<div 
 id="inputBoxParent" 
 count="0">
      ...
</div>

用js更新

inputBoxParent.setAttribute('count', value.length)

CSS -在伪元素中添加内容为attr(attributeName)

.input-box-container::after{
  content: attr(count);
}

你完蛋了!!

const inputBoxParent = document.getElementById("inputBoxParent"); const handleOnChange = (value) => { inputBoxParent.setAttribute('count', value.length) } .input-box-container { position: relative; width: 200px; } .input-box-container::after{ position: absolute; bottom: 8px; right: 10px; height: 10px; width: 20px; content: attr(count); } <h4> Type some text inside the box and click outside to see resule i.e. pseudo element content change</h4> <div id="inputBoxParent" class="input-box-container" count="0"> <input type="text" id="inputBox" placeholder="type some thing" onchange="handleOnChange(this.value)" onkeyup="handleOnChange(this.value)" /> </div>