我对一个简单的脚本有疑问。我试图让一个按钮在你点击它时改变它的背景颜色。我在这里搜索并用谷歌搜索。根据我的发现,我的脚本没有任何问题。你能帮我解决这个问题吗?
这是我的 CSS 样式表:
body {
height: 100% 100vh;
background: linear-gradient(90deg, #122221 50%, #116699 50%);
}
#btn {
background-color: white;
width: 200px;
height: 100px;
}
这是我的 html:
<!DOCTYPE html>
<meta charset="UTF-8">
<html lang="en-US">
<html>
<head>
<link rel="stylesheet" href="learning.css">
<script>
function foo(){
var x = document.getElementById("btn");
if (x.style.background-color == "white"){
x.style.background-color = "green";
}
else {
x.style.background-color = "white";
}
}
</script>
</head>
<body>
<button id = "btn" onclick = "foo()"> click me </buttonM>
</body>
</html>
最佳答案
background-color
应该是 backgroundColor
:
function foo(){
var x = document.getElementById("btn");
if (x.style.backgroundColor == "white")
{
x.style.backgroundColor = "green";
}
else {
x.style.backgroundColor = "white";
}
}
注意: style.backgroundColor
将在第一次点击时返回空字符串,因此最好使用 getComputedStyle
,这样它会返回附加的样式从 CSS 到元素。
希望这对您有所帮助。
使用 getComputedStyle
的代码段 (从第一次点击开始工作):
function foo(){
var x = document.getElementById("btn");
var bg_color = window.getComputedStyle(x,null).getPropertyValue("background-color");
if (bg_color == "rgb(255, 255, 255)")
{
x.style.backgroundColor = "green";
}
else {
x.style.backgroundColor = "white";
}
}
body {
height: 100% 100vh;
background: linear-gradient(90deg, #122221 50%, #116699 50%);
}
#btn {
background-color: white;
width: 200px;
height: 100px;
}
<button id="btn" onclick = "foo()"> click me </button>
关于javascript - 按钮背景颜色onclick变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43394685/