JS Classlist删除

时间:2018-02-02 11:15:38

标签: javascript html css

我在从元素中删除类时遇到问题。我已经尝试了很多方法,但它仍然无法工作。问题是什么? 谢谢!



function boxClick(e) {
  e.currentTarget.classList.add("valami");
  e.currentTarget.setAttribute("id", "currentBox");
}

function closeBox() {
  var openedBox = document.getElementsByClassName("valami");
  var curBox = document.getElementById("currentBox");
  curBox.classList.remove("valami");
}

var gridBoxok = document.getElementsByClassName("grid-box-content");
for (var i = 0; i < gridBoxok.length; i++) {
  gridBoxok[i].addEventListener('click', boxClick, false);
}

var close = document.getElementsByClassName("close-container");
for (var i = 0; i < close.length; i++) {
  close[i].addEventListener('click', closeBox, false);
}
&#13;
.valami {
  outline: solid yellow 1px;
}
&#13;
<div class="grid-container">
  <div class="grid-box">
    <div class="grid-box-content">
      <div class="close-container">
        fdfadsf
        <i class="fas fa-times"></i>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您只需要在关闭事件处理程序中停止事件冒泡,否则在closeBox(删除类)事件后继续向上传播DOM树,当它到达.grid-box-content时,它会导致boxClick(添加类)再次执行。

试试这个:

function closeBox(e) {
  e.stopPropagation(); // <--- add this line
  var openedBox = document.getElementsByClassName("valami");
  var curBox = document.getElementById("currentBox")
  curBox.classList.remove("valami");
}

演示:https://jsfiddle.net/cy5ukzcg/

答案 1 :(得分:1)

我认为你绑定你关闭的方式是不正确的,我会像下面这样做。还.add.remove don't work in certain browsers,所以我改变了添加和删除类的方式:

function boxClick(e) {
  e.currentTarget.classList += " valami";
  e.currentTarget.removeEventListener('click', boxClick); // remove box click
  e.currentTarget.addEventListener('click', closeBox);  // bind close click
}

function closeBox(e) {
  e.currentTarget.classList = e.currentTarget.className.replace(" valami", "");
  e.currentTarget.removeEventListener('click', closeBox); // remove close click
  e.currentTarget.addEventListener('click', boxClick);  // bind box click
}


var gridBoxok = document.getElementsByClassName("grid-box-content");
for (var i = 0; i < gridBoxok.length; i++) {
  gridBoxok[i].addEventListener('click', boxClick);
}
.valami {
  outline: solid yellow 1px;
}
<div class="grid-container">
  <div class="grid-box">
    <div class="grid-box-content">
      <div class="close-container">
        fdfadsf
        <i class="fas fa-times"></i>
      </div>
    </div>
  </div>
</div>

编辑,抱歉,没有意识到绑定绑定是在父级中的另一个元素上。所以紧密绑定是正确的,但你需要像dfsq的答案一样停止点击传播。虽然这将作为更新班级列表的替代方式(如果您需要支持ie)

,请留下这个