项目中时常会需要用到使用javascript来动态控制为元素(:before,:after)的样式,但是我们都知道javascript或jquery并没有伪类选择器。本文我们主要介绍了javascript实现修改伪类样式的方法以及代码实现过程。
HTML
Hi, this is a plain-old, sad-looking paragraph tag.
CSS
.red::before { content: 'red'; color: red; }
立即学习“Java免费学习笔记(深入)”;
方法一
使用JavaScript或者jQuery切换
元素的类名,修改样式。
.green::before { content: 'green'; color: green; } $('p').removeClass('red').addClass('green');
立即学习“Java免费学习笔记(深入)”;
立即学习“Java免费学习笔记(深入)”;
方法二
在已存在的
document.styleSheets[0].addRule('.red::before','color: green'); document.styleSheets[0].insertRule('.red::before { color: green }', 0);
立即学习“Java免费学习笔记(深入)”;
方法三
创建一份新的样式表,并使用JavaScript或jQuery将其插入到
中// 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);
立即学习“Java免费学习笔记(深入)”;
jQuery
$('<style>.red::before{color:green}</style>').appendTo('head');
立即学习“Java免费学习笔记(深入)”;
方法四
使用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');
相关推荐:
以上就是JavaScript实现修改伪类样式的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号