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

Categories

0 votes
3.8k 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...