项目中时常会需要用到使用JavaScript来动态控制为元素(:before,:after)的样式,但是我们都知道JavaScript或jQuery并没有伪类选择器。这里总结一下几种常见的方法。
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>中动态插入新样式。
document.styleSheets[0].addRule('.red::before','color: green');document.styleSheets[0].insertRule('.red::before { color: green }', 0);方法三
创建一份新的样式表,并使用JavaScript或jQuery将其插入到<head>中
// Create a new style tagvar style = document.createElement("style");// Append the style tag to headdocument.head.appendChild(style);// Grab the stylesheet objectsheet = style.sheet// Use addRule or insertRule to inject stylessheet.addRule('.red::before','color: green');sheet.insertRule('.red::before { color: green }', 0);jQuery
$('<style>.red::before{color:green}</style>').appendTo('head');方法四
使用HTML5的data-属性,在属性中使用attr()动态修改。
<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');以上就是我们为大家整理的四种方法,如果大家有更好的方法,可以在下方的留言区讨论。