使用Vanilla JS在点击元素外部时删除元素属性

4

我可以在单击其他相同类型的div元素之外或另一个div上删除元素属性吗?这是我的代码:

HTML:

<div id="container">
  <div data-something></div>
  <div data-something></div>
</div>

JavaScript:

var elements = document.querySelectorAll("[data-something]");    

Array.prototype.forEach.call(elements, function(element) {

  // Adding
  element.onclick = function() {
    this.setAttribute("data-adding", "");
  };

  // Removing -- Example
  element.onclickoutside = function() {
     this.removeAttribute("data-adding");
  };

});
2个回答

6

我会在文档上使用一个点击处理程序,然后从任何具有该属性但不在冒泡路径中的元素中删除该属性。

document.addEventListener("click", function(e) {
    Array.prototype.forEach.call(document.querySelectorAll("*[data-adding][data-something]"), function(element) {
        var node, found = false;
        for (node = e.target; !found && node; node = node.parentNode) {
            if (node === element) {
                found = true;
            }
        }
        if (!found) {
            element.removeAttribute("data-adding");
        }
    });
}, false);

...or something along those lines.

Live Example:

    document.addEventListener("click", function(e) {
      Array.prototype.forEach.call(document.querySelectorAll("*[data-adding]"), function(element) {
        var node, found = false;
        for (node = e.target; !found && node; node = node.parentNode) {
          if (node === element) {
            found = true;
          }
        }
        if (!found) {
          element.removeAttribute("data-adding");
        }
      });
    }, false);
*[data-adding] {
  color: red;
}
<div data-adding data-something>One</div>
<div data-adding data-something>Two</div>


2
你可以在全局点击事件处理程序中使用 Node.contains() 来检查点击是否在元素外部,并适当地处理事件:

box = document.getElementById('box');
lastEvent = document.getElementById('event');

box.addEventListener('click', function(event) {
  // click inside box
  // (do stuff here...)
  lastEvent.textContent = 'Inside';
});

window.addEventListener('click', function(event) {
  if (!box.contains(event.target)) {
    // click outside box
    // (do stuff here...)
    lastEvent.textContent = 'Outside';
  }
});
#box {
  width: 200px;
  height: 50px;
  background-color: #ffaaaa;
}
<div id="box">Click inside or outside me</div>

<div>Last event: <span id="event">(none)</span>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接