我们都听说过css伪类但是并没有听说过javascript也有伪类,项目中时常会需要用到使用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切换
元素的类名,修改样式。
.green::before { content: 'green'; color: green; } $('p').removeClass('red').addClass('green');
方法二
立即学习“Java免费学习笔记(深入)”;
在已存在的
document.styleSheets[0].addRule('.red::before','color: green'); document.styleSheets[0].insertRule('.red::before { color: green }', 0);
方法三
创建一份新的样式表,并使用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);
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');
以上就是我们为大家整理的四种如何用JavaScript修改伪类样式的方法,希望对大家有帮助。
相关推荐:
以上就是如何用JavaScript修改伪类样式的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号