<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>事件的传播顺序(冒泡模型与捕捉模型先捕捉再冒泡),阻止,移除</title>
<style>
#outside{
width: 600px;
height:600px;
margin:0px auto;
border: 1px solid red;
}
#inside{
width: 400px;
height:400px;
margin:0 auto;
margin-top: 100px;
border: 1px solid #008000;
}
#remove{
margin: 0px auto;
margin-top:20px;
height: 100px;
width:200px;
border: 1px solid red;
}
</style>
<script type="text/javascript">
/**
* 事件的传播顺序(冒泡模型与捕捉模型),阻止事件与效果,移除事件
* 1.正因为有了元素的嵌套,才有元素事件的执行顺序之分
* 2.当点击内层div执行顺序会是怎样
* addEventListener('click','function',false) false代表冒泡事件,true代表捕捉事件
* stopPropagation() 停止事件的传播
* 阻止事件效果,比如当提交表单时,让其不跳转,在标准的W3C中是通过事件的preventDefault=true属性来控制的
* 而在ie模型中是通过returnValue=false属性值来实现的
* obj.removeEventListener()
* 冒泡事件是一次从内而外执行事件,而捕捉是从外到里捕捉事件
*/
</script>
</head>
<body>
<div id="outside">
<div id="inside">
</div>
</div>
<div id="remove">
<button onclick="add();">事件的监听</button>
<button onclick="remove();">事件的移除</button>
</div>
<script>
var outside=document.getElementById("outside");
var inside=document.getElementById("inside");
outside.addEventListener('click',function(ev){
alert("outside");
//阻止事件的传播
ev.stopPropagation();
//阻止事件的效果,ie中需要用returnValue=false属性设置
ev.preventDefault=true;
},false);
inside.addEventListener('click',function(){
alert("inside");
},false);
/**
* 事件的舰艇与移除
*
*/
function add(){
var remove=document.getElementById("remove");
remove.addEventListener('click',bodyalert,false);
alert("事件被监听了");
}
function remove(){
var remove=document.getElementById("remove");
remove.removeEventListener('click',bodyalert,false);
alert("事件被移除了");
}
function bodyalert(){
alert("事件被监听了");
}
</script>
</body>
</html>
转载于:https://my.oschina.net/u/998304/blog/363133