javascript - 使用 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>
任何帮助都会得到帮助
解决方案
你正在寻找<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>
推荐阅读
- php - 使用 Server to Server API 打开 SSL 和 PHP
- php - 将带有新键的数组推送到现有数组
- html - CSS 属性 Max-Width 功能混淆
- php - 如何将 CURLOPT_POSTFIELDS 用于带大括号的查询字符串?- PHP
- c# - 有没有办法将组合框选择写入由 tableLayoutPanel 读取然后显示的文本文件?
- mysql - 如何根据用户从下拉列表中选择的项目加载行轴
- vue.js - vite配置文件根本不生效
- reactjs - 一起使用reactjs和spring boot时的spring boot刷新问题
- c++ - 在 C++ 中以 gedit 的形式关闭程序中的文件
- django - 将动态选择列表传递给基于类的视图中的视图