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

后端 未结 2 1280
自闭症患者
自闭症患者 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;   
    }
    
    0 讨论(0)
  • 2021-01-05 06:01

    Another solution to this can be a second element. It lies beneath the dropdown, but goes over the viewport and has your click-handler, that closes the dropdown. This elements existence (CSS:display, Vue:v-if...) should be linked to the dropdown.

    This has the (dis-)advantage, that a click outside does not register on the element you click on, so that is a deciding factor for this mehtod. With background-color and higher opacity it can be used for pop-ups.

    CSS:

    .dropdown {
      ...
      z-index: 2;
    }
    .overlay {
      display:none;
      position: fixed;
      bottom: 0;
      top: 0;
      right: 0;
      left: 0;
      opacity: 0;
      z-index: 1;
    }
    .overlay.open {
      display:block;
    }
    
    0 讨论(0)
提交回复
热议问题