Detect click outside div using javascript

后端 未结 7 1895
無奈伤痛
無奈伤痛 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:39

    Try this solution it uses pure javascript and it solves your problem. I added css just for better overview... but it is not needed.

    document.getElementById('outer-div').addEventListener('click', function(){
      alert('clicked outer div...');
    });
    
    document.getElementById('inner-div').addEventListener('click', function(e){
      e.stopPropagation()
      alert('clicked inner div...');
    });
    #outer-div{
      width: 200px;
      height: 200px;
      position: relative;
      background: black;
    }
    
    #inner-div{
      top: 50px;
      left: 50px;
      width: 100px;
      height: 100px;
      position: absolute;
      background: red;
    }

提交回复
热议问题