Detect click outside div using javascript

后端 未结 7 1896
無奈伤痛
無奈伤痛 2020-12-02 13:10

I\'d like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, i

7条回答
  •  再見小時候
    2020-12-02 13:44

    It depends on the individual use case but it sounds like in this example there are likely to be other nested elements inside the main div e.g. more divs, lists etc. Using Node.contains would be a useful way to check whether the target element is within the div that is being checked.

    window.addEventListener('click', function(e){   
      if (document.getElementById('clickbox').contains(e.target)){
        // Clicked in box
      } else{
        // Clicked outside the box
      }
    });
    

    An example that has a nested list inside is here.

提交回复
热议问题