Detect clicks outside of specific div and all of it's children

后端 未结 2 1303
自闭症患者
自闭症患者 2021-01-05 05:04

I\'ve been reading the following:

https://css-tricks.com/dangers-stopping-event-propagation/

I want to implement this in a proper and safe way.

I wo

2条回答
  •  长情又很酷
    2021-01-05 05:49

    You're on the right way and only need one little change inside your code. Instead of only checking if the event.target is the same as the div, also check if the div contains the event target:

    var container = document.getElementsByClassName('container')[0];
    document.addEventListener('click', function( event ) {
      if (container !== event.target && !container.contains(event.target)) {    
        console.log('clicking outside the div');
      }
    });
    

    If for some reason HTMLnode.contains() is not supported (safari, im looking at you), you can use following snippet to check if an element contains another:

    function childOf( node, ancestor ) {
        var child = node;
        while (child !== null) {
            if (child === ancestor) return true;
            child = child.parentNode;
        }
        return false;   
    }
    

提交回复
热议问题