还在寻找相同问题的解决方案的人,使用jQuery可以做到以下几点:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
此示例说明单击按钮:changeBefore 时,.graph:before 的值将根据新的动态值发生变化。
有关更改:before 或:after 元素样式或获取其内容的更多说明:
假设你的 HTML 是这样的:
<div id="something">Test</div>
然后你在 CSS 中设置它的 :before 并像这样设计它:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
请注意,我还在元素本身中设置了content 属性,以便您以后可以轻松将其取出。
现在有一个button 点击它,您想将 :before 的颜色更改为绿色,并将其字体大小更改为 30px。您可以通过以下方式实现:
在某个类.activeS 上使用您需要的样式定义一个css:
.activeS:before{
color:green !important;
font-size:30px !important;
}
现在您可以通过将类添加到您的 :before 元素来更改 :before 样式,如下所示:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
如果你只想获取:before的内容,可以这样做:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
希望对你有帮助