HTML 动态修改伪类内容

10 min read

一、html代码部分

<div id="box" data-content-before=":before" data-content-after=":after">box盒子</div>

二、css样式部分

<style>
    *{
        padding: 0;
        margin: 0;
    }
    body{
        padding: 0;
        margin: 0;
    }
    #box{
        width: 200px;
        height: 200px;
        position: fixed;
        top: calc(50% - 100px);
        left: calc(50% - 100px);
        background: #0877FF;
        border-radius: 10px;
        text-align: center;
        box-shadow: 1px 2px 3px -1px;
    }
    #box:after{
        content: attr(data-content-after);
        position: relative;
        top: -120px;
        left: -160px;
        width: 104px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        border-radius: 10px;
        background: orange;
        box-shadow: 1px 2px 3px -1px;
        display: block;
    }
    #box:before{
        content: attr(data-content-before);
        position: relative;
        top: 0;
        right: -260px;
        width: 104px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        border-radius: 10px;
        background: #39c778;
        box-shadow: 1px 2px 3px -1px;
        display: block;
    }
</style>

三、js代码部分

<script type="text/javascript">
    var box = document.getElementById('box');
    
    var boxBeforeVal = box.attributes[1].value; 
    var boxAfterVal = box.attributes[2].value;
            
    //console.log(boxBefore);//输出为   :before
    //console.log(boxAfter);//输出为  :after
            
    //下面可以自定义boxBeforeVal和boxAfterVal的值
    box.attributes[1].value = ':before伪元素';
    box.attributes[2].value = ':after伪元素';
</script>