在前端开发中我们会经常用到伪元素,有时候需要通过 js 来动态修改伪元素的样式,在这里小胡给大家列举了 3 种动态修改伪元素样式的方法
第一种:通过追加类名来动态改变伪元素的样式
CSS:
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
.box::after {
content: '';
display: block;
width: 100px;
height: 100px;
background-color: pink;
}
.green::after {
background-color: green;
}
</style>
JS:
<div class="box">努力学前端的小胡</div>
<script>
// 获取伪元素真实盒子的类名
const box = document.querySelector('.box')
// 给盒子追加伪元素的类名覆盖之前伪元素的样式
box.classList.add('green')
</script>
效果:
第二种:通过 stylesheet.insertRule 方法插入新的样式规则
CSS:
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
.box::after {
content: '';
display: block;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
JS:
<body>
<div class="box">努力学前端的小胡</div>
<script>
// 拿到当前的第一个样式表
const styleSheets = document.styleSheets[0];
// 在当前样式表插入 CSS 新规则,插入到第一个样式表的最下面(不加第二个参数默认在当前样式表的第一位插入)
styleSheets.insertRule(`.box::after { background-color: green }`, styleSheets.cssRules.length)
</script>
</body>
效果:
第三种:通过追加 style 标签动态改变伪元素
CSS:
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
.box::after {
content: '';
display: block;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
JS:
<body>
<div class="box">努力学前端的小胡</div>
<script>
第一种:
// 创建 style 标签
const style = document.createElement('style')
// 在 dom 上动态追加 style 标签
document.head.appendChild(style)
// 拿到样式表
const sheet = style.sheet
// 在样式表内插入 CSS 新规则
sheet.insertRule(`.box::after { background-color: green }`)
第二种:
// 创建 style 标签
const style = document.createElement('style')
// 设置 style 标签类型
style.type = 'text/css'
// 把 style 动态追加到页面
document.body.appendChild(style)
// 把 CSS 样式给 style 标签
style.innerText = `.box::after { background-color: green }`
</script>
</body>
效果:
总结:3种方法最好的就是第一种动态追加类名,其他两种都是动态追加 style 标签,性能不好就算了,可维护性也不高,到时候出问题人家想看 CSS 从哪里来的都找不到!