繁体   English   中英

JavaScript 用于更换<div>按下按钮的颜色</div><div id="text_translate"><p>当我的 html 和 JS 代码在同一个文件中时,我有点不确定为什么我的代码似乎不起作用。 当 html 和 JS 分开时,似乎工作正常。 有人可以指出我的错误....我是新手!</p><p> <strong>HTML:</strong></p><pre> &lt;div class="main"&gt; &lt;div class="light"&gt;&lt;/div&gt; &lt;button onclick="chngCol()" id="burn"&gt;Burn!&lt;/button&gt; &lt;/div&gt;</pre><p> <strong>JavaScript:</strong></p><pre> 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"; } }</pre><p> <strong>CSS:</strong></p><pre> .light{ width: 50px; height: 50px; background-color:#00ffff; }</pre><p> 所有代码都在同一个文档中,带有适当的标签,但是我在第一个 { 调用 chngCol.</p></div>

[英]JavaScript for changing a <div> colour from a button press

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

HTML:

<div class="main">
    <div class="light"></div>
    <button onclick="chngCol()" id="burn">Burn!</button>
</div>

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";       
      }
   }

CSS:

    .light{
        width: 50px;
        height: 50px;
        background-color:#00ffff;
    }

所有代码都在同一个文档中,带有适当的标签,但是我在第一个 { 调用 chngCol.

有很多问题。

  • chngCol() {不是有效的 JS。 function chngCol() {const 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);
 .light { width: 50px; height: 50px; background-color: #00ffff; } #burn { width: 150px; font-weight: 700; }
 <div class="main"> <div class="light"></div> <button id="burn">Burn!</button> </div>

document.getElementByClass 选择器是一个数组选择器。 为了 select 你的元素你应该 select 数组的第一个元素。 试试这个:

document.getElementsByClassName('light')[0].style.background

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM