阅读 882

js动态修改:after:before伪元素content值

今天做了一个有关js如何绑定动态修改伪类的content的内容,运用到的有( :before 和 :after 伪元素、CSS content 属性、data-* H5新属性、js)等技术。
基本原理:
1)首先给box盒子添加 [data-content-before=":before"]和[ data-content-after=":after"]属性;
2)其次添加html标签和style样式;
3)在样式里添加box元素的:before伪元素和:after 伪元素;
4):before伪元素和:after 伪元素里各自添加content属性;
5)content 和 attr 配合使用:
content: attr(data-content-after);content: attr(data-content-before);
这样content可以获取到box添加data-content-after属性里的值:after(before同理)

6)创建的两个伪类属性.png


6)最后通过js获取到box对象,通过box对象attributes找到添加的 [data-content-before=":before"]和[ data-content-after=":after"]属性的value,有了value值,这就可以进行动态修改 before伪元素和:after 伪元素里的content值;
以此现在做一个笔记以便以后使用,Hope to help you.


废话不多说,直接上代码

一、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>

四、效果图

刷新页面前.png

刷新页面后.png



作者:一岁倾城
链接:https://www.jianshu.com/p/0d1f0d482e81


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐