栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

项目中时常会需要用到使用Javascript来动态控制为元素(:before,:after)的样式,但是我们都知道Javascript或jQuery并没有伪类选择器。这里总结一下几种常见的方法。

HTML

Hi, this is a plain-old, sad-looking paragraph tag.

CSS
.red::before {
    content: 'red';
    color: red;
}

方法一

使用Javascript或者jQuery切换

元素的类名,修改样式。

.green::before {
    content: 'green';
    color: green;
}
$('p').removeClass('red').addClass('green');

方法二

在已存在的中动态插入新样式。

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

$('.red::before{color:green}').appendTo('head');

方法四

使用HTML5的data-属性,在属性中使用attr()动态修改。

Hi, this is plain-old, sad-looking paragraph tag.

.red::before { content: attr(data-attr); color: red; } $('.red').attr('data-attr', 'green');

作者:Helkyle
原文地址:http://www.w3ctrain.com/2015/07/21/modify-pseudo-elements-css/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/233706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号