阻止事件流冒泡

今天又有个朋友问我“点击某个按钮触发某个事件,点击这个按钮之外的任何一个地方触发另一个事件”的功能怎么写。其实有两个方法。一种是在按钮上加个事件,document上加另一个事件,但是在按钮的事件最后,加上阻止事件流冒泡的语句,不冒到document上就行。另一种方法,就是在document上监听事件,然后通过对event.target进行判断,如果当前元素是按钮,执行某个事件,如果不是,执行另一事件。我自己习惯性用第一种方法,放上一个简单的例子吧。

========================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿当制作</title>
</head>

<body>
<input type="button" value="不阻止冒泡的按钮" id="btn" />
<input type="button" value="阻止冒泡的按钮" id="btn2" />
</body>
<script type="text/javascript">
    document.onclick = function(){
        alert("我是body");
    }
    document.getElementById("btn").onclick=function(e){
        alert("我是按钮");
    }
    document.getElementById("btn2").onclick=function(e){
        alert("我是按钮");
        if(document.all) window.event.cancelBubble=true;
        else e.stopPropagation();
    }   
</script>
</html>
原文地址:https://www.cnblogs.com/cly84920/p/4427009.html