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

英文原文:modify-pseudo-elements-css
译文地址:http://w3ctrain.com/2015/07/21/modify-pseudo-elements-css/

项目中时常会需要用到使用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');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 8,849评论 0 44
  • 第一章 jQuery简介 1-1 jQuery简介 1.简介 2.优势 3.特性与工具方法 1-2 环境搭建 进入...
    mo默22阅读 5,613评论 0 11
  • 原文链接 http://blog.poetries.top/2016/10/20/review-jQuery 关注...
    前端进阶之旅阅读 16,788评论 18 503
  • 通过jQuery,您可以选取(查询,query)HTML元素,并对它们执行“操作”(actions)。 jQuer...
    枇杷树8824阅读 3,885评论 0 3
  • 今天很早就来到所里,趁工作开始前抓时间在青狮营学了“VIP入营指南”系列课程,学会了用Mac自带工具制作头像、用S...
    柿柿子阅读 1,378评论 1 1