在父母身上听“mousedown”,但让“click”传给孩子们

时间:2016-07-25 12:39:53

标签: javascript dom

我有一个div来监听mousedown事件。 div有一些子按钮(绝对位于div之外)。我希望能够单击这些按钮。但是当我按下鼠标按钮时,父div拦截mousedown事件。我可以测试.target成员如果它发生在按钮上则忽略该事件,但似乎我从未在这些按钮上获得click事件。

有没有办法解决这个问题而不添加另一个祖先div

1 个答案:

答案 0 :(得分:0)

您可以使用event.target == this

示例:

<html>
    <head>
       <style>
           div {
               width: 100px;
               background-color: yellow;
               height: 100px;
           }
       </style>
    </head>
    <body>
        <div id="d">I am div
            <button id="btn1">Button1</button>
        </div>
        <script>
            var divMousedown = document.getElementById("d");
            var Child = document.getElementById("btn1");
            divMousedown.onmousedown = function(event) {
                if(event.target == this)
                alert("You Mouse down on Div");
            }
            Child.onclick = function(event){
                if(event.target == this)
                    alert("You Click on Button")
            }
        </script>
    </body>
</html>