技术文章分类(180)

技术随笔(11)

js阻止冒泡事件(cancelBubble,stopPropagation)

两种方法可以阻止冒泡

1、设置event.cancelBubble=true;

2、调用event.stopPropagation();

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body onclick="alert('body');">
    <input id="Button" type="button" value="button" onclick="clickBtn(event)" />
    <input id="Button1" type="button" value="button1" onclick="clickBtn1(event)" />
    <input id="Button2" type="button" value="button2" onclick="clickBtn2(event)" />
</body>
<script type="text/javascript">
    function clickBtn(event){
        alert("button");
    }
    function clickBtn1(event)
    {
        event=event?event:window.event;
        event.cancelBubble=true;
        alert("button1");
    }
    function clickBtn2(event){
        alert("button2")
        event.stopPropagation();
    }
</script>

</html>

 

据说(未经本人测试,只是据说,如有差错,概不负责):

event.cancelBubble在moz内核无效;

所以建议使用event.stopPropagation();

 

 

posted @ 2014-05-05 21:30  坤哥MartinLi  阅读(308)  评论(0编辑  收藏  举报