Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

如何用JS动态修改内嵌CSS 的属性值?

通过页面按钮控制 多个容器的宽度,变大变小

<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>

<style>
.box { width:100px; height:60px; }
</style>

通过JS,修改样试 style 内的 .box 的 width 值,来达到变动的需求,
有什么好的办法。求大神指点。

另外,有没有什么操作,改变了值,STYLE 不重新渲染的,

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

可以用css变量

<div class="box box1" id="btn"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<style>
    :root{
        --width: 500px
    }
    .box{
        height: 100px;
        width: 300px;
        background: #000;
        margin-top: 10px;
    }
    .box1{
        width: var(--width)
    }
</style>
<script>
    document.getElementById('btn').onclick = function(){
        document.documentElement.style.setProperty('--width', '800px');
    }
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...