gpt4 book ai didi

javascript - 如何在JavaScript中更改背景颜色?

转载 作者:行者123 更新时间:2023-12-04 00:53:33 27 4
gpt4 key购买 nike

每次单击按钮时,我都试图更改包装器的背景颜色。单击它时,应该将其更改为数组中的随机颜色。对初学者有什么想法吗? CSS也是用SASS完成的,因此看起来可能不太漂亮。



function change_Color() {
var color = ["blue", "red", "green", "yellow"];
document.getElementById("wrapper").style.backgroundColor = color;
}

body {
margin: 0;
}

* {
box-sizing: border-box;
}

#wrapper {
width: 100%;
height: 100vh;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
button {
padding: 10px;
background: orange;
color: white;
border: none;
border-radius: 10px;
font-size: 2rem;
transition: .5s ease;
&:hover {
box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
cursor: pointer;
}
&:focus {
outline: 0;
color: skyblue;
}
}
}

<div id="wrapper">
<button onclick="change_Color()">Click me!</button>
</div>

最佳答案

检查这个。我在CSS中合并了主体和包装器,并为主体指定了ID



var colors = ["red", "blue", "green", "yellow"];
function changeColor() {
document.getElementById("body").style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];}

#body {
margin: 0;
box-sizing: border-box;
width: 100%;
height: 100vh;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
button {
padding: 10px;
background: orange;
color: white;
border: none;
border-radius: 10px;
font-size: 2rem;
transition: .5s ease;
&:hover {
box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
cursor: pointer;
}
&:focus {
outline: 0;
color: skyblue;
}
}

<body id='body'>
<button onclick="changeColor();">Click me!</button>
</body>

关于javascript - 如何在JavaScript中更改背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62143561/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com