簡體   English   中英

JavaScript切換按鈕顏色

[英]JavaScript to toggle button colour

我正在嘗試建立一個包含多個按鈕的頁面,當任務完成時,所有按鈕均從紅色切換為綠色。 但是,我希望他們能夠在出現錯誤時切換回去。 到目前為止,我具有以下功能:

  <button id="button">button</button> <script> function changeColor(button) { var thisButton = document.getElementById(button) if (thisButton.style.background == '#0f0') { thisButton.style.background='#0f0'; } else { thisButton.style.background='#f00'; } } </script> 

如果我使用“紅色”或“綠色”作為顏色,則可以使用,但是如果我使用上述十六進制或rgb(255,0,0),則if始終返回“ false”。 有什么想法我做錯了嗎?

您正在將背景色與十六進制的短版進行比較。 將其與完整的6位數十六進制進行比較:

if (thisButton.style.background.toLowerCase() == '#00ff00')

但是考慮使用一些類。 切換類是更好的方法。

您沒有使用正確的十六進制代碼。

紅色是#FF0000 ,綠色是#008000

看起來瀏覽器正在“自動校正”所應用的顏色。 在我的測試中,如果我設置thisButton.style.background = 'rgb(255,0,0)' ,然后使用console.log(thisButton.style.background)讀回該值,則它將在每個逗號后添加一個空格,給我rgb(255, 0, 0) 看到這個小提琴演示。

我建議添加一個data-color屬性,它將完全在您的控制之下。

  function changeColor(button) {
    var thisButton = document.getElementById(button)

    if (thisButton.getAttribute('data-color') === 'red') {
      thisButton.style.background='#0f0';
      thisButton.setAttribute('data-color', 'green');
    } else {
      thisButton.style.background='#f00';
      thisButton.setAttribute('data-color', 'red');
    }

  }

背景顏色樣式屬性高度依賴於瀏覽器。 Chrome可能會輸出rgb(0, 255, 0) #00FF00 rgb(0, 255, 0)而Internet Explorer可能會輸出#00FF00

嘗試在您自己的模型中保留按鈕的狀態。

const myButtonModel = {
    color: "#0F0"
};

function changeColor() {
    const buttonElement = document.getElementById("button");

    myButtonModel.color = myButtonModel.color === "#0F0" ? "#F00" : "#0F0";

    buttonElement.style.background = myButtonModel.color;
}

如果您想擁有一個類似(btn-toggled)的類,則可以按以下步驟進行:

const buttonElement = document.getElementById("button");
buttonElement.classList.toggle("btn-toggled")

它對我有用,也許嘗試使用document.querySelector而不是document.getElementById

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM