css JavaScript背景单击颜色更改

3xiyfsfu  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(117)

我想改变我的网站多种颜色。但如何?我的网站主体bg的颜色变好了,但是我不能改变部分的背景色。帮助我
我正在尝试一些javascript体bg-color change.it工作,但我想改变我的部分bg-color

e4yzc0pl

e4yzc0pl1#

考虑到你想改变id=outer-section的元素的背景。
HTML:

<section id="outer-section">
    <section id="inner-section">
    </section>
</section>

JS:

document.getElementById("outer-section").style.background = "red"

// or using parentElement
document.getElementById("inner-section").parentElement.style.background = "red"
rkttyhzu

rkttyhzu2#

我不知道我是否理解正确,但你可以试试下面的代码。

const btn = document.getElementById('my-btn');
 const section = document.getElementById('my-section');
 const colors = ["red", "green", "blue"];
 const colorIndex = 0;
    
 btn.addEventListener('click', function() {
     const newColorIndex = parseInt((Math.random() * (3 - 1) + 1).toFixed());
     section.style.backgroundColor = colors[newColorIndex - 1];
 });
#my-section {
     height: 300px;
     border: 1px solid #000;
 }
        
 #my-btn {
     margin-bottom: 10px;
 }
<button id="my-btn">Click Me</button>
<div id="my-section"></div>

相关问题