首页 > 解决方案 > 使用 JS 在多个元素上更改背景颜色,然后在选择另一个元素时更改

问题描述

我在表格中有一系列图片,当点击其中一张图片时,td的背景会改变颜色。但是只能选择一个。

这是我到目前为止所拥有的,但是它改变了每个被点击的人的背景:

<table>
  <tr>
    <td width="100px" valign="top" id="panel1">
      <img src="pic1.jpg" id="setDesign1">
      <script>
        document.getElementById("setDesign1").addEventListener("click", function() {
          this.style.backgroundColor = "red";
          return false;
        });
      </script>
    </td>
    <td width="100px" valign="top" id="panel2">
      <img src="pic2.jpg" id="setDesign2">
      <script>
        document.getElementById("setDesign2").addEventListener("click", function() {															 
        this.style.backgroundColor = "red";
        return false;
        });
      </script>
    </td>
    <td width="100px" valign="top" id="panel3">
      <img src="pic3.jpg" id="setDesign3">
      <script>
        document.getElementById("setDesign3").addEventListener("click", function() {
          this.style.backgroundColor = "red";
          return false;
        });
      </script>
    </td>
  </tr>
</table>

任何帮助都会得到帮助

标签: javascripthtml

解决方案


你正在寻找<input type="radio">

input[type=radio]:checked + label>img {
  border: 1px solid #fff;
  box-shadow: 0 0 3px 3px #090;
}

.input-hidden {
  position: absolute;
  left: -9999px;
}
<input 
  type="radio" name="emotion" 
  id="sad" class="input-hidden" />
<label for="sad">
  <img 
    src="//cdn0.iconfinder.com/data/icons/interface-63/24/402_-_Interface_radio_button_off_indeterminate_edit_radio_icon-128.png" 
    alt="I'm sad" />
</label>

<input 
  type="radio" name="emotion"
  id="happy" class="input-hidden" />
<label for="happy">
  <img 
    src="//cdn0.iconfinder.com/data/icons/interface-63/24/402_-_Interface_radio_button_off_indeterminate_edit_radio_icon-128.png" 
    alt="I'm happy" />
</label>


推荐阅读