簡體   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