继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

GD_SeHun
关注TA
已关注
手记 160
粉丝 570
获赞 3.9万

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

作者:Helkyle
原文地址:http://www.w3ctrain.com/2015/07/21/modify-pseudo-elements-css/

打开App,阅读手记
24人推荐
发表评论
随时随地看视频慕课网APP

热门评论

最后一个只是修改了内容,并不能修改到颜色吧

不错

最后一个没看懂。

查看全部评论