有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
当前回答
一种有效但不太有效的方法是在文档中添加带有新内容的规则,并用类引用它。根据需要,类可能需要为内容中的每个值提供唯一的id。
$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');
其他回答
为什么要添加类或属性,当你可以添加一个样式头
$('head').append('<style>.span:after{ content:'changed content' }</style>')
$ (' .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进行样式化。
谢谢大家! 我设法做了我想做的事:D http://jsfiddle.net/Tfc9j/42/ 让我们来看看
我想有一个外部div的不透明度是不同于内部div的不透明度和改变点击somwewhere;) 谢谢!
$('#ena').on('click', function () {
$('head').append("<style>#ena:before { opacity:0.3; }</style>");
});
$('#duop').on('click', function (e) {
$('head').append("<style>#ena:before { opacity:0.8; }</style>");
e.stopPropagation();
});
#ena{
width:300px;
height:300px;
border:1px black solid;
position:relative;
}
#duo{
opacity:1;
position:absolute;
top:50px;
width:300px;
height:100px;
background-color:white;
}
#ena:before {
content: attr(data-before);
color: white;
cursor: pointer;
position: absolute;
background-color:red;
opacity:0.9;
width:100%;
height:100%;
}
<div id="ena">
<div id="duo">
<p>ena p</p>
<p id="duop">duoyyyyyyyyyyyyyy p</p>
</div>
</div>
这是我第一次在给出我自己的答案之前没有阅读所有给出的答案,所以我希望这不会让我…
在我的情况下,这是需要的图标附加到一个,div和按钮元素,这与<i class="icon-class"></i>的工作有点不同,因为他们没有icon-class类。添加class="icon-class"会破坏样式。
相反,我为它们添加了一个数据图标属性,其中的值应该在element:: {content: "HERE"}之前,然后这个相当简单的JavaScript就会处理剩下的事情。
{
const fakeIcons = document.querySelectorAll('[data-icon]')
for (const iconElement of fakeIcons) {
const fakeClass = 'fake-' + Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('')
const beforeContent = iconElement.getAttribute('data-icon')
iconElement.classList.add(fakeClass)
const style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = `
.${fakeClass}::before {
content: "${beforeContent}" !important;
}
`
document.getElementsByTagName('head')[0].appendChild(style)
}
}
代码解释道:
选择具有指定属性(data-icon)的所有元素 循环遍历它们 随机生成一个以fake-开头的类名,后面跟着一个随机的字母数字字符串 获取data-icon属性的值 向元素中添加随机生成的类 在伪元素设置内容之前为::创建样式 在<head> HTML元素的末尾添加样式