简体   繁体   English

使用javascript更改div中的背景颜色

[英]Change background color in div, using javascript

I just wanted a button to change some colors.我只是想要一个按钮来改变一些颜色。 For example I have the background in "wrap" div and some borders in other divs.例如,我在“环绕”div 中有背景,在其他 div 中有一些边框。

#wrap {

    width:100vw;
    height: 100vh;

    margin:0 auto;

    font: italic bold 15px arial, sans-serif;

    background-color: rgb(0, 14, 51);

    overflow-y: scroll;

    background-size: cover;

}
    #middleBarExtra{


        margin-top: 130px;

        height: 1px;
        width:100%;

        border: solid 5px rgb(200, 64, 235);

        border-radius: 30px;

}

How can I change the background color in "wrap" and the border color in "midlleBarExtra", with a function in javascript?如何使用javascript中的函数更改“wrap”中的背景颜色和“midlleBarExtra”中的边框颜色?

I tried this, but didn't work:我试过这个,但没有用:

function changeColors(){
    
    document.getElementById("wrap").style.background = "white";

}
document.getElementById("wrap").style.backgroundColor = "white";

If you change only styles, it's a better idea to add/remove classes instead of using completely js.如果您只更改样式,最好添加/删除类而不是完全使用 js。

 function changeColors(){ document.getElementById("wrap").classList.toggle("new-styles"); }
 #wrap { width:100vw; height: 100vh; margin:0 auto; background: rgb(0, 14, 51); } #middleBarExtra{ margin-top: 130px; height: 1px; width:100%; border: solid 5px rgb(200, 64, 235); border-radius: 30px; } #wrap.new-styles { background: rgb(255,255,255); } .new-styles #middleBarExtra { border-color: red; }
 <button onclick="changeColors()">Change</button> <div id="wrap"> <div id="middleBarExtra"></div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM