英文原文:modify-pseudo-elements-css
譯文地址:http://w3ctrain.com/2015/07/21/modify-pseudo-elements-css/
項(xiàng)目中時(shí)常會(huì)需要用到使用JavaScript來(lái)動(dòng)態(tài)控制為元素(:before,:after)的樣式亡哄,但是我們都知道JavaScript或jQuery并沒有偽類選擇器蹄咖。這里總結(jié)一下幾種常見的方法嗡综。
HTML
<p class="red">Hi, this is a plain-old, sad-looking paragraph tag.</p>
CSS
.red::before {
content: 'red';
color: red;
}
方法一
使用JavaScript或者jQuery切換<p>
元素的類名成翩,修改樣式捡鱼。
.green::before {
content: 'green';
color: green;
}
$('p').removeClass('red').addClass('green');
方法二
在已存在的<style>
中動(dòng)態(tài)插入新樣式。
document.styleSheets[0].addRule('.red::before','color: green');
document.styleSheets[0].insertRule('.red::before { color: green }', 0);
方法三
創(chuàng)建一份新的樣式表凑耻,并使用JavaScript或jQuery將其插入到<head>
中
// Create a new style tag
var style = document.createElement("style");
// Append the style tag to head
document.head.appendChild(style);
// Grab the stylesheet object
sheet = style.sheet
// Use addRule or insertRule to inject styles
sheet.addRule('.red::before','color: green');
sheet.insertRule('.red::before { color: green }', 0);
jQuery
$('<style>.red::before{color:green}</style>').appendTo('head');
方法四
使用HTML5的data-
屬性纳令,在屬性中使用attr()
動(dòng)態(tài)修改。
<p class="red" data-attr="red">Hi, this is plain-old, sad-looking paragraph tag.</p>
.red::before {
content: attr(data-attr);
color: red;
}
$('.red').attr('data-attr', 'green');