美文网首页
h5阻止事件冒泡

h5阻止事件冒泡

作者: __笑我一世沉沦丶 | 来源:发表于2019-05-08 16:34 被阅读0次

event.stopPropagation() 方法阻止事件冒泡到父元素,阻止任何父事件处理程序被执行。
在绑定的事件中使用阻止事件冒泡:

$("p").click(function(event){
alert("The p element was clicked.");
});

以下是示例

<script>
$(document).ready(function(){
  $("p").click(function(event){
      event.stopPropagation();
    alert("The p element was clicked.");
  });
  $("div").click(function(){
    alert("The div element was clicked.");
  });
});
</script>

<body>
    <div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
This is a div element.
    <p style="background-color:pink">This is a p element, in the div element. <br></p>
</div>
</body>

在元素中写绑定事件

<input type="text" onclick="clickInput(this,1)" id="input1" class=""/>
//此时要用this来转换成上面的e

 function clickInput(target,id){
        var e=window.event || arguments.callee.caller.arguments[0];
        e.preventDefault();
        e.stopPropagation();
        
        console.log(id)
    }

  • 绑定的事件需要统一,如果一个使用onfocus,另一个使用onclick,则不会阻止事件冒泡
  • 阻止事件冒泡兼容ie8
function clickInput(target,id){
        var e=window.event || arguments.callee.caller.arguments[0];
        if ( e && e.stopPropagation ) {
            // 因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        } else {
            // 否则,我们需要使用IE的方式来取消事件冒泡
            window.event.cancelBubble = true;
        }
    }

相关文章

网友评论

      本文标题:h5阻止事件冒泡

      本文链接:https://www.haomeiwen.com/subject/xikvoqtx.html