使用JavaScript修改伪类样式的方法

前言

项目中时常会需要用到使用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>

Javascript:

// 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()动态修改

<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');

猜你喜欢

转载自www.cnblogs.com/kunmomo/p/12358005.html