【问题标题】:change color of an element on click in pure JS在纯 JS 中单击时更改元素的颜色
【发布时间】:2016-06-12 23:08:39
【问题描述】:

我有以下JS代码:

<div> item1 </div>
<div> item2 </div>
<div> item3 </div>

var x = document.querySelectorAll('div');

for(var i = 0; i < x.length; i++){
  x[i].addEventListener("click", function (){
    for(var i = 0; i < x.length; i++){
      if(x[i].style.color === ""){
        x[i].style.color = "red"
      } else {
        x[i].style.color = ""
      }
    }
 });
}

我想在单击每个项目时更改颜色,而不是更改所有项目的颜色。如何更改颜色并且仅在单击的元素上?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您正在遍历处理程序中的所有&lt;div&gt;s。更简单的方法是:

    for(var i = 0; i < x.length; i++) {
      if (x[i] !== this) {
        x[i].style.color = "";
      }
    }
    if (this.style.color === "red") {
      this.style.color = "";
    } else {
      this.style.color = "red"
    }
    

    在这种情况下,this 指的是被点击的元素。

    【讨论】:

    • 可以使用三元运算符:this.style.color = this.style.color === "" ? "red" : ""
    • @Tushar 这不太清楚,尤其是对于新编码员。
    • 谢谢,但是如果我只想将一个元素设为红色怎么办?
    • @Alex 你什么意思?如果你把它放在事件处理程序中,那么它应该只改变点击的元素。
    • 我的意思是如何防止其他元素被选中为红色,而其中一个元素被选中为红色?类似于单选按钮,但只有颜色
    【解决方案2】:

    与其循环遍历所有 div 并向它们附加侦听器,不如只向窗口添加 1 个侦听器,如果它是 div,则更改其颜色。

    window.addEventListener('click', function(event) {
        const target = event.target; // what you clicked on
        if(target.tagName !== 'DIV') {
            return; // not a <div>, stop the function
        }
    
        const color = target.style.color;
        target.style.color = color? '' : 'red'; // color is set then clear it, otherwise set to 'red'
    });
    

    或者:

    const divs = document.querySelectorAll('div');
    Array.from(divs).forEach(div => {
        div.addEventListener('click', changeColor);
    });
    
    function changeColor() {
        let color = this.style.color;
        this.style.color = color? '' : 'red';
    }
    

    另外,您需要将 Javascript 代码包装在 &lt;script&gt; /* JS here */ &lt;/script&gt; 标记中。

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2016-01-14
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多