JavaScript实现修改伪类样式

小云云
小云云 原创
2017-12-07 15:58:13 1239浏览

项目中时常会需要用到使用JavaScript来动态控制为元素(:before,:after)的样式,但是我们都知道JavaScript或jQuery并没有伪类选择器。本文我们主要介绍了JavaScript实现修改伪类样式的方法以及代码实现过程。

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

相关推荐:

伪类选择器汇总

PHP中的伪类型和伪变量

php函数之常规参数函数和伪类型参数函数

以上就是JavaScript实现修改伪类样式的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。