更改--css - backgroundColor函数(纯javascript)不起作用

时间:2017-03-28 14:39:59

标签: javascript html css

有人能告诉我为什么在执行onclick后改变颜色在这里不起作用吗?

function butt(color) {
    if(document.getElementById("bt").style.backgroundColor=="green"){
            document.getElementById("bt").style.backgroundColor="purple";
    }
};
document.getElementById("bt").addEventListener("click", function() {
    butt("green")
});
#bt {
    background-color:yellow;
    border-radius:10%;
    padding:10px;
    margin:20px;
}            
<div class="row">
    <div id="forbutton">
        <button type="button" id="bt">It's me MrButton !</button>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

你只是传递字符串&#34;绿色&#34;通过功能。详情请参阅代码段。

<强>段

&#13;
&#13;
// pass the string through function
function butt(color) {

  // If string is "green"...
  if (color === "green") {

    // Reference #bt and change it's backgroundColor to purple
    document.getElementById("bt").style.backgroundColor = "purple";
  }

};

// Register #bt to click event, when clicked...
document.getElementById("bt").addEventListener("click", function() {

  // Call butt() function passing the string "green"
  butt("green")
});
&#13;
#bt {
  background-color: yellow;
  border-radius: 10%;
  padding: 10px;
  margin: 20px;
}
&#13;
<div class="row">
  <div id="forbutton">
    <button id="bt">It's me MrButton !</button>
  </div>
&#13;
&#13;
&#13;