通过js动态改变伪元素before或after的content值

核心:使用 data-* 给html设置数据属性,接着在css中通过attr()获取html的属性值,再通过js修改属性值来改变content

1、dom部分

使用 data-* 在html元素上嵌入自定义数据属性,以便通过js读|写数据属性(具体方法见js部分)

<div class="box1 box2" data-before='原始值' ref='box' ></div>
复制代码

2、css部分

在css中,首先初始化样式,接着通过 attr(name) 访问html元素上定义的数据属性

注意:attr() 理论上能用于所有的CSS属性,但目前支持的仅有伪元素的 content 属性,其他的属性和高级特性目前是实验性的

.box1 {//初始化样式
    &:before {
      content: '';
      position: absolute;
      left: 7px;
      font-size: 14px;
      color: #f44;
   }
}

.box2::before{
   content: attr(data-before);//增加attr属性
}
复制代码

3、js部分

修改数据属性data-before的值,进而修改content

读取方法:Element.getAttribute(name)

写入方法:Element.setAttribute(name, value)

this.$refs['box'].setAttribute('data-before', parseInt(Math.random())*100)
复制代码

Demo

<template>
    <div>
        <div class="box1 box2" ref="box" data-before='*'></div>
        <button @click="handleChange">切换content</button>
    </div>
</template>

<script>
export default {
    methods: {
        handleChange() {
            let txt = parseInt(Math.random()*100);
            this.$refs['box'].setAttribute("data-before", txt);
        }
    }
}
</script>

<style lang="scss" scoped>
.box1::before {//初始化样式
    content: '*';
    position: absolute;
    left: 7px;
    font-size: 14px;
    color: #f44;
}


.box2{//添加attr属性
    &:before {
        content: attr(data-before);
    }
}
</style>
复制代码

引用:
参考来源1
参考来源2参考来源3

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享