[removed] Click anywhere in body except the one element inside it

前端 未结 4 813
温柔的废话
温柔的废话 2021-02-13 13:43

I want to be able to click anywhere inside the body except that one specific element. I can\'t find out what\'s wrong with the code I have done.

When I click on the one

相关标签:
4条回答
  • 2021-02-13 14:24

    Instead of stopping propagation on the except element, I'd prefer something like this:

    var wrapper = document.querySelector('wrapper');  
    
    document.addEventListener('click', function(e) {
       if ( !wrapper.contains(e.target) ) {
           // Do something when user clicked outside of wrapper element
       }
    })
    
    0 讨论(0)
  • 2021-02-13 14:25

    You need to stopPropagation to the outer element.

    Here's a simple illustration: http://jsfiddle.net/5mhqrhwk/3/

    var body = document.getElementById('wrapper');
    var except = document.getElementById('except');
    
    body.addEventListener("click", function () {
        alert("wrapper");
    }, false);
    except.addEventListener("click", function (ev) {
        alert("except");
        ev.stopPropagation(); //this is important! If removed, you'll get both alerts
    }, false);
    

    HTML:

    <div id="wrapper">
        <center>
            <div id="except"></div>
        </center>
    </div>
    
    0 讨论(0)
  • 2021-02-13 14:26

    You are missing one piece to this. You need to stop the event from bubbling up from the except object if it is clicked

    except.addEventListener("click", function(event){event.stopPropagation()}, false);
    
    0 讨论(0)
  • 2021-02-13 14:29

    You don't really need any flags to do this. Just listen on body click and do different thing depending on the item clicked (event.target). This code should do exactly what you wanted (based on your code):

    var body = document.getElementById('wrapper');
    var except = document.getElementById('except');
    
    if(body.addEventListener)
      body.addEventListener("click", bodyClick, false);
    else
      body.attachEvent("onclick", bodyClick);
    
    function bodyClick(event){
      if(event.target != except)
        except.style.display = "none";
    }
    
    0 讨论(0)
提交回复
热议问题