簡體   English   中英

更改按鈕的背景顏色 - 單擊時更改,單擊另一個按鈕時刪除

[英]Changing Background Colour of Button - Change when clicked, remove when another button is clicked

第一次發帖 - 試圖在其他地方找到解決方案,但無法找到。

我創建了一個按鈕網格。 單擊按鈕 1 后,我希望背景更改為預設顏色。 當單擊另一個按鈕(按鈕 2)時,我希望按鈕(1)背景變回原來的,然后是新單擊的按鈕(按鈕 2)以呈現預設顏色。

這是到目前為止編寫的 HTML:

    <div class="tip-select">
      <p class="ttext">Select Tip %</p>
      <div class="tip">
        <div class="five-tip btn tips">5%</div>
        <div class="ten-tip btn tips">10%</div>
        <div class="fifteen-tip btn active-tip tips">15%</div>
        <div class="twentyfive-tip btn tips">25%</div>
        <div class="fifty-tip btn tips">50%</div>
        <div class="custom btn tips">Custom</div>
      </div>
    </div>

這是到目前為止編寫的 Javascript:

tips.forEach(function (mov) {
  mov.addEventListener("click", handleClick);
});


function handleClick(event) {
tips.forEach(function (val) {
  if (event.target.innerHTMl == val.innerHTMl) {
    val.classList.add("active-tip");
    console.log(val);
  }
  });
}

這是當前的設計供參考:

改變網格

我的想法是遍歷節點列表並根據所選按鈕將活動提示分配為 class。 目前,盡管所有按鈕在單擊時都會改變顏色。

首先, JavaScript 區分大小寫,因此innerHTMl應為innerHTML 但這不是實現您想要的效果的合理方法。

此外, tips需要是一個數組,因此使用querySelectorAll來返回一個實時集合(“實時”意味着只存儲對元素的引用而不是元素)。 要將其制成數組,請使用Array.from()

首先remove所有active-tip styles,然后將新的添加到所需的元素中。

 tips=Array.from(document.querySelectorAll('.tips')); tips.forEach(function (mov) { mov.addEventListener("click", handleClick); }); function handleClick(e) { tips.forEach((t)=>t.classList.remove("active-tip")); e.target.classList.add("active-tip"); }
 .active-tip {color:red}
 <div class="tip-select"> <p class="ttext">Select Tip %</p> <div class="tip"> <div class="five-tip btn tips">5%</div> <div class="ten-tip btn tips">10%</div> <div class="fifteen-tip btn active-tip tips">15%</div> <div class="twentyfive-tip btn tips">25%</div> <div class="fifty-tip btn tips">50%</div> <div class="custom btn tips">Custom</div> </div> </div>

You you can add a prameter to function which is the id or class of your div so when your function called your function take the innertext of the div with you id you get from pramerter.

我建議您比較節點對象而不是它們的innerHtml 此外,您錯過了重置所有非選定節點的else情況(刪除active-tip類)。

這是一個例子

let tips = Array.from(document.getElementsByClassName('tips'))

tips.forEach(function (mov) {
  mov.addEventListener("click", handleClick);
});

function handleClick(event) {
  tips.forEach(function (val) {
    if (val == event.target) {
      val.classList.add("active-tip");
    } else {
      val.classList.remove("active-tip");
    }
  });
}

以及此處的完整代碼示例https://codepen.io/beezital/pen/OJxoxmK

暫無
暫無

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

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