通过首先单击选择div并取消选择其他选项,然后再单击同一div取消选择它

时间:2020-07-01 17:43:47

标签: javascript html jquery

我希望遇到以下情况:

  • 一次只能选择一个格(完成
  • 通过单击div可以将其选中,而其他div则应保持未选中状态(完成
  • ,通过单击已选择的div ,应取消选择该div,其他div也将保持未选中状态( 要做

我在实现最后一个功能时遇到问题,在该功能上,通过单击已选择的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>

JSFiddle

1 个答案:

答案 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>

相关问题