我正在尝试创建一个按钮来更改我的 HTMl 页面的背景颜色。 下面是我的代码,但是我的代码似乎不起作用任何人都可以帮助我吗?
var colors = ["red", "blue", "green"];
var colorIndex = 0;
function changeColor() {
var col =
document.getElementById("body");
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor =
colors[colorIndex];
colorIndex++;
}
/* This is to Style My Button */
.button {
position: center;
background-color: #c2c3c4;
border: none;
font-size: 28px;
color: #FFFFFF;
padding: 20px;
width: 200px;
text-align: center;
-webkit-transition-duration: 0.4s; /*
Safari */
transition-duration: 0.4s;
text-decoration: none;
overflow: hidden;
cursor: pointer;
}
.button:after {
content: "";
background: #f1f1f1;
display: block;
position: absolute;
padding-top: 300%;
padding-left: 350%;
margin-left: -20px !important;
margin-top: -120%;
opacity: 0;
transition: all 0.8s
}
.button:active:after {
padding: 0;
margin: 0;
opacity: 1;
transition: 0s
}
<html>
<head></head>
<body>
<button class="button" onclick="changeColor();">Change Colour</button>
</body>
</html>
这是我对代码的最后一次尝试,它不起作用但是它确实给了我我想要的按钮样式,任何添加或解决将不胜感激。
最佳答案
你只需要调用你的 body ,
document.getElementsByTagName("body")[0]
var colors = ["red", "blue", "green"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementsByTagName("body")[0];
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
}
/* This is to Style My Button */
.button {
position: center;
background-color: #c2c3c4;
border: none;
font-size: 28px;
color: #FFFFFF;
padding: 20px;
width: 200px;
text-align: center;
-webkit-transition-duration: 0.4s; /*
Safari */
transition-duration: 0.4s;
text-decoration: none;
overflow: hidden;
cursor: pointer;
}
.button:after {
content: "";
background: #f1f1f1;
display: block;
position: absolute;
padding-top: 300%;
padding-left: 350%;
margin-left: -20px !important;
margin-top: -120%;
opacity: 0;
transition: all 0.8s
}
.button:active:after {
padding: 0;
margin: 0;
opacity: 1;
transition: 0s
}
<button class="button" onclick="changeColor();">Change Colour</button>
关于javascript - 尝试创建一个改变背景颜色的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623889/