“如果不是div”onclick事件不包括儿童div

时间:2016-11-27 14:24:33

标签: javascript

使用vanilla JS,我正在尝试创建一个关闭点击 - 例如,如果单击了主体并且它不是单击的某个元素,则关闭该元素。

但是,当您单击指定的元素(它没有关闭)时它会起作用,但是当您单击该元素的任何子节点时它会触发该事件。我希望if语句包含该父元素的任何子节点,以及父节点本身。

HTML:

<ul id="NavSocial-target" class="Nav_social">
    <li class="Nav_social_item">Facebook</li>
    <li class="Nav_social_item">Twitter</li>
    <li class="Nav_social_item">Google</li>
</ul>

<ul class="Nav_options FlexList">
    <li class="Nav_options_item FlexList_item" id="NavSocial-trigger">Social</li>
    <li class="Nav_options_item FlexList_item">Curr/Lang</li>
</ul>

使用Javascript:

this.triggerDOM =  document.getElementById('NavSocial-trigger');
this.targetDOM =  document.getElementById('NavSocial-target');

// If not list item that triggers model && if not model itself
document.getElementsByTagName('body')[0].onclick = (e) => {
    if(e.target !== this.triggerDOM && e.target !== this.targetDOM){
        this.removeClass();
    }  
};

1 个答案:

答案 0 :(得分:1)

我认为this.triggerDOM是您要忽略的元素。您需要查看点击是否通过传递元素,并带有循环:

this.triggerDOM =  document.getElementById('NavSocial-trigger');
// ...
document.body.addEventListener("click", e => {
    var element = e.target;
    while (element && element !== document.body) {
        if (element === this.triggerDOM) {
            // It was a click in `this.triggerDOM` or one of its
            // children; ignore it
            return;
        }
        element = element.parentNode;
    }
    // It wasn't a click anywhere in `this.triggerDOM`
    this.removeClass();
}, false);

关于上述内容的附注:

  • document.getElementsByTagName("body")[0]只是写document.body的很长的路: - )
  • 使用onclick并不适合其他人;如果您仍然需要支持严重过时的浏览器,请在IE8及更早版本上使用addEventListener(或attachEvent。)
  • 接受单个参数的箭头函数在参数列表周围不需要()(当然,如果您喜欢该样式,可以将它们放在那里)。

工作示例:

this.triggerDOM = document.getElementById('NavSocial-trigger');
// ...
document.body.addEventListener("click", e => {
  var element = e.target;
  while (element && element !== document.body) {
    if (element === this.triggerDOM) {
      // It was a click in `this.triggerDOM` or one of its
      // children; ignore it
      return;
    }
    element = element.parentNode;
  }
  // It wasn't a click anywhere in `this.triggerDOM`
  this.triggerDOM.parentNode.removeChild(this.triggerDOM);
}, false);
#NavSocial-trigger {
  border: 1px solid #ddd;
  background-color: #dd0;
}
<!-- Note the really deep nesting -->
<div><div><div><div><div><div><div><div><div><div>
  Click
  <div>
    anywhere
    <div>
      on
      <div>
        this
        <div>
          page
          <div>
            except
            <div id="NavSocial-trigger">
              here
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</div></div></div></div></div></div></div></div></div>