js如何动态控制伪元素

比如我希望动态控制下面的 rotate

           &:after {
                content: '';
                width: 100%; 
                height: 100%;
                position: absolute;
                transform: rotate(30deg);
                border-radius: 50%;
            }
阅读 5.9k
9 个回答

伪元素不是真的元素,不能通过dom获取到,所以不能操作,像1l说的,多写几个类名,或者用别的标签替换掉伪元素

js 修改伪元素属性的方法:

css

.left-up-ico::before {
    background: rgba(30, 136, 255, 1);
}

html

<div class="left-up-ico"></div>

js

 document.styleSheets[0].addRule('.left-up-ico::before ','background: rgb(165, 165, 165) !important');

需要几个状态就设定几个类名,对应切换类名即可

通过控制类来控制变化 如果是动态的需要计算的变化 就不要使用伪元素

不知道你的需求是什么?
我想到transition
transition

<!DOCTYPE>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style>
        div:after{
            content:'just test 1';
        }
    </style>
    <style>
        .custom_edit_style{

        }
    </style>
</head>
<body>
<div></div>
<input type="button" value="change" />
<script>
    function findCustomEditStyle(selector='.custom_edit_style'){
        const styles=document.styleSheets;
        for(let i=0;i<styles.length;i++){
            try{
                const style=styles[i];
                if(style.cssRules[0].selectorText==selector){
                    return style;
                }
            }catch(e){
                continue;
            }
        }
        return undefined;
    }
    function addRules(selector,rules){
        var style=findCustomEditStyle();
        if(!style){
            return false;
        }
        var index=style.cssRules.length;
        style.addRule(selector,rules,index);
    }
    var index=2;
    document.querySelector('input').onclick=function(){
        addRules('div:after','content:"just test '+(index++)+'";');
    }
</script>
<script src="//q.qunarzz.com/open_m_train/prd/scripts/zepto@5f84d4ac791c84f64346aec65b2a0083.js"></script>
</body>
</html>

通过添加css rule试试

尝试通过添加删除class来进行操作?

新手上路,请多包涵

多加类名啊 ( 根据需求 js动态来添加删除类名啊)

  • 动态插入style标签吧!
  • 为什么不直接创建一个 absolute 元素?
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题