Javascript Detect click event outside of div

前端 未结 10 936
孤城傲影
孤城傲影 2020-11-27 06:07

I have a div with id=\"content-area\", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaSc

相关标签:
10条回答
  • 2020-11-27 06:36

    Use document.activeElement to see which of your html elements is active.

    Here is a reference: document.activeElement in MDN

    0 讨论(0)
  • 2020-11-27 06:42

    Here is the fiddle : http://jsfiddle.net/uQAMm/1/

    $('#outercontainer:not(#contentarea)').on('click', function(event){df(event)} );
    function df(evenement)
    {
        var xstart = $('#contentarea').offset().left;
        var xend = $('#contentarea').offset().left + $('#contentarea').width();
    
        var ystart = $('#contentarea').offset().top;
        var yend = $('#contentarea').offset().top + $('#contentarea').height(); 
    
        var xx = evenement.clientX;
        var yy = evenement.clientY;
    
        if ( !(  ( xx >=  xstart && xx <=  xend ) && ( yy >=  ystart && yy <=  yend )) )
        {
            alert('out');
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-27 06:47
    $('#outer-container').on('click', function (e) {
         if (e.target === this) {
            alert('clicked outside');
         }
    });
    

    This is for the case that you click inside the outer-container but outside of the content-area.

    0 讨论(0)
  • 2020-11-27 06:48

    Put this into your document:

    <script>
    document.onclick = function(e) {
      if(e.target.id != 'content-area') alert('you clicked outside of content area');
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题