用于通过按下按钮更改 <div> 颜色的 JavaScript

K.H*_*ock 0 html javascript css onclick

当我的 html 和 JS 代码在同一个文件中时,我有点不确定为什么我的代码似乎不起作用。当 html 和 JS 分开时,似乎工作正常。有人可以指出我的错误......我是新手!!

HTML:

<div class="main">
    <div class="light"></div>
    <button onclick="chngCol()" id="burn">Burn!</button>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

chngCol() {
    if(document.getElementByClass('light').style.background == "#00ffff")
      { 
       document.getElementByClass('light').style.background = "#ffff00"; 
      } 
       else if(document.getElementByClass('light').style.background == "ffff00")
      {
       document.getElementByClass('light').style.background = "#ff00ff"; 
      }
       else if(document.getElementByClass('light').style.background == "#ff00ff")
      { 
       document.getElementByClass('light').style.background = "#00ffff";       
      }
   }
Run Code Online (Sandbox Code Playgroud)

CSS:

    .light{
        width: 50px;
        height: 50px;
        background-color:#00ffff;
    }
Run Code Online (Sandbox Code Playgroud)

所有代码都在带有适当标签的同一个文档中,但是在调用 chngCol.h 后,我在第一个 { 时在 Chrome 控制台中遇到了错误。

mpl*_*jan 5

有很多问题。

  • chngCol() {不是有效的 JS。无论function chngCol() {ORconst chngCol = () =>
  • 你需要document.getElementsByClassName("light")[0]或更好,document.querySelector(".light")
  • 如果未先在脚本中设置元素的背景颜色,则无法读取该元素的背景颜色。

我想你的意思是这样做:

let cnt = 0;
const colors = ["#00ffff", "#ffff00", "#ff00ff"];
const chngCol = () => {
  cnt++;
  if (cnt >= colors.length) cnt = 0; // wrap
  document.querySelector('.light').style.background = colors[cnt]; // use the array
}
document.getElementById("burn").addEventListener("click", chngCol);
Run Code Online (Sandbox Code Playgroud)
.light {
  width: 50px;
  height: 50px;
  background-color: #00ffff;
}

#burn {
  width: 150px;
  font-weight: 700;
}
Run Code Online (Sandbox Code Playgroud)
<div class="main">
  <div class="light"></div>
  <button id="burn">Burn!</button>
</div>
Run Code Online (Sandbox Code Playgroud)