事件捕获和冒泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件捕获和冒泡</title>
<style type="text/css">
.box{
width: 600px;
height: 600px;
margin: 0 auto;
background-color: red;
overflow: hidden;
}
.mid{
width: 400px;
height: 400px;
margin: 100px;
background-color: gold;
overflow: hidden;
}
.item{
width: 200px;
height: 200px;
background-color: blue;
margin: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="mid">
<div class="item"></div>
</div>
</div>
</body>
<script type="text/javascript">
var box = document.getElementsByClassName("box")[0];
var mid = document.getElementsByClassName("mid")[0];
var item = document.getElementsByClassName("item")[0];
box.addEventListener("click", function(){
console.log("box");
}, false);
mid.addEventListener("click", function(){
console.log("mid");
}, false);
item.addEventListener("click", function(ev){
ev.cancelBubble = true;
ev.stopPropagation();
if (ev.stopPropagation) {
ev.stopPropagation();
} else{
ev.cancelBubble = true;
}
console.log("小明");
ev.preventDefault();
ev.returnValue = false;
return false;
}, false);
</script>
</html>
事件绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件绑定</title>
<style type="text/css">
body{
margin: 0;
padding: 0;
background-color: black;
}
.redDiv{
width: 200px;
height: 200px;
background-color: red;
margin: 20px auto;
}
</style>
</head>
<body>
<div class="redDiv"></div>
</body>
<script type="text/javascript">
var redDiv = document.getElementsByClassName("redDiv")[0];
redDiv.addEventListener("click", f1, false);
redDiv.addEventListener("click", f2, false);
function f1(){
console.log(1);
}
function f2(){
console.log(2);
}
redDiv.removeEventListener("click", f2, false);
</script>
</html>
http://blog.csdn.net/huzongnan/article/list