javascript - 按钮背景颜色onclick变化

标签 javascript html css

我对一个简单的脚本有疑问。我试图让一个按钮在你点击它时改变它的背景颜色。我在这里搜索并用谷歌搜索。根据我的发现,我的脚本没有任何问题。你能帮我解决这个问题吗?

这是我的 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/

相关文章:

javascript - 选中/取消选中复选框时更改相应标签的文本

android - 禁用 html css 设计文本框的问题?

html - 如何更改 CSS flex-box 列的宽度?

css - 将鼠标悬停在 IE 中的嵌入式视频上时,下拉菜单消失

javascript - javascript函数也是一种对象吗?

javascript - 使用javascript设置按钮的值

javascript - 使用服务进行数据绑定(bind)不适用于 Angular JS

html - css中的边框样式结束

javascript - jquery 拖放表格

css - 我应该如何使用 ASP.NET MVC 4 进行布局管理?