簡體   English   中英

如何根據條件更改 Javascript 中的活動文本和懸停文本?

[英]How to change active and hovering text in Javascript depending on condition?

我有這些用作按鈕的 div。

 var color_switch = 1; var tmbtns = document.getElementsByClassName("time-button"); for (var i = 0; i < tmbtns.length; i++) { tmbtns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active2"); current[0].className = current[0].className.replace(" active2", ""); this.className += " active2"; }); }
 .time-buttons{ float: left; }.time-button{ float: left; padding: 0.2rem; padding-bottom: 0.3rem; margin-left: 1px; margin-right: 1px; cursor: pointer; color: lightgrey; width: 30px; text-align: center; }.active2, .time-button:hover{ color: red; }
 <div class="time-buttons"> <div class="time-button active2"><small>2h</small></div> <div class="time-button"><small>8h</small></div> <div class="time-button"><small>1d</small></div> <div class="time-button"><small>3d</small></div> <div class="time-button"><small>1w</small></div> <div class="time-button"><small>1m</small></div> </div>

我怎樣才能做到當 color_switch 改變時,文本改變的顏色也會改變? 那么當 color_switch = 1 時,文本以紅色突出顯示,當 color_switch = 2 時,文本以藍色突出顯示,等等?

例如,您可以使用 switch 來設置當前元素應該被繪制成什么顏色。

 switch (color_switch) {
  case 1:
    this.style.color = "red";
    break;

  case 2:
    this.style.color = "blue";
    break;
 }

有很多可能的解決方案,這里是其中之一: https://jsfiddle.net/9bj86L72/

我認為,最好的做法是不要在 js 中合並 css 代碼,最好的是創建修飾類並將其用於 map 它在 js 中。 例如:

.time-buttons.type1 .time-button:hover {
  color: red;
}

.time-buttons.type2 .time-button:hover {
  color: red;
}

在 js 中根據 de color_switch 設置修飾符 class

document.querySelector('.time-buttons').className = document.querySelector('.time-buttons').className + " type" + color_switch

請查看示例https://codepen.io/ricardocermeno/pen/ExojdVZ

暫無
暫無

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

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