有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
有什么方法来选择/操作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');
其他回答
你也可以将内容传递给带有data属性的伪元素,然后使用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设置父样式。
例如,我想改变:before的颜色样式,然后我设置:
.my-style::before{
color: inherit;
}
然后我用javascript改变了.my-style元素的颜色样式:
document.querySelector(".my-style").style.color = red;
工作完成了,超级简单
下面是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”!}> < /风格”);
您可以创建一个伪属性,也可以使用一个现有的属性,并在伪元素的样式表中继承它。
var switched = false; // Enable color switching setInterval(function () { var color = switched ? 'red' : 'darkred'; var element = document.getElementById('arrow'); element.style.backgroundColor = color; // Managing pseudo-element's css // using inheritance. element.style.borderLeftColor = color; switched = !switched; }, 1000); .arrow { /* SET FICTIONAL PROPERTY */ border-left-color:red; background-color:red; width:1em; height:1em; display:inline-block; position:relative; } .arrow:after { border-top:1em solid transparent; border-right:1em solid transparent; border-bottom:1em solid transparent; border-left:1em solid transparent; /* INHERIT PROPERTY */ border-left-color:inherit; content:""; width:0; height:0; position:absolute; left:100%; top:-50%; } <span id="arrow" class="arrow"></span>
似乎它对“content”属性不起作用:(
我已经创建了一个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!"'
});