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

前端 未结 4 808
温柔的废话
温柔的废话 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: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:

提交回复
热议问题