JavaScript实现修改伪类样式

js教程评论665 views阅读模式

项目中时常会需要用到使用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教程其它相关文章!

企鹅博客
  • 本文由 发表于 2019年9月14日 09:39:56
  • 转载请务必保留本文链接:https://www.qieseo.com/393725.html

发表评论