我希望遇到以下情况:
我在实现最后一个功能时遇到问题,在该功能上,通过单击已选择的div取消选择它,其他已经正常工作的功能应该可以像以前一样工作。有人可以帮我使它正常工作吗?
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
var selectedEl = document.querySelector(".selected");
if (selectedEl) {
selectedEl.classList.remove("selected");
}
this.classList.add("selected");
}, false);
}
.optionsecoptions {
width: 400px;
padding-left: 10px;
height: 40px;
background: #bbb8b8;
float: left;
font-size: 20px;
cursor: pointer;
}
.optionsecoptions:hover,
.optionsecoptions:active {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
.selected {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
<div style="margin-top:10px;">
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>
</div>
答案 0 :(得分:0)
您可以这样做:
// If there was a selected element which is not this
if (selectedEl && selectedEl !== this) {
selectedEl.classList.remove("selected");
}
// Toggle this
this.classList.toggle("selected");
如评论中所述,您的样式有些误导。您可能想在:hover
和.selected
上使用不同的样式。下面的演示也对此进行了更改。
演示:
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
var selectedEl = document.querySelector(".selected");
// If there was a selected element which is not this
if (selectedEl && selectedEl !== this) {
selectedEl.classList.remove("selected");
}
// Toggle this
this.classList.toggle("selected");
}, false);
}
.optionsecoptions {
width: 400px;
padding-left: 10px;
line-height: 40px;
background: #eceded;
font-size: 16px;
cursor: pointer;
font-family: Arial, Helvetica, sans-serif;
transition: background-color 0.1s ease-in;
}
.optionsecoptions:hover { background-color: #bfe5ff; }
.optionsecoptions:active { background-color: #2d546f; color: #ffffff; }
.selected { background-color: #226fa3; color: #ffffff; }
.selected:hover { background-color: #4d99cc; }
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>