有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
当前回答
$ (' .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 >
其他回答
下面是访问: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');
下面的解决方案告诉你如何用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>
下面是HTML:
<div class="icon">
<span class="play">
::before
</span>
</div>
“before”上的计算样式是内容:“VERIFY TO WATCH”;
下面是我的两行jQuery代码,它们使用了添加一个额外的类来特别引用这个元素,然后附加一个样式标签(带一个!important标签)来改变sudo元素内容值的CSS:
$(“span.play:eq(0)”).addClass('G');
$('体').append(“<时尚>。G:在{重要内容:“NewText”!}> < /风格”);
我已经创建了一个jQuery插件来添加css伪规则,如使用.css()为特定的元素。
插件代码和测试用例在这里(更新的Fiddle) 用例作为简单的CSS图像弹出这里
用法:
$('body')
.css({
backgroundColor: 'white'
})
.cssPseudo('after', {
content: 'attr(title) ", you should try to hover the picture, then click it."',
position: 'absolute',
top: 20, left: 20
})
.cssPseudo('hover:after', {
content: '"Now hover the picture, then click it!"'
});
为什么要添加类或属性,当你可以添加一个样式头
$('head').append('<style>.span:after{ content:'changed content' }</style>')