js事件代理
可以方便我们多个同组对象添加统一事件,简化代码,事件代理使用的是事件冒泡特性(事件会随着子父级层次向外传递),点击子元素触发事件后在父元素获取,通过事件的目标对象确定具体触发的子元素。
js原生事件绑定
,兼容方法见我的博客另一篇文章:http://blog.csdn.net/qq_14886653/article/details/52495000
简单例子,解释下js事件代理
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
width: 500px;
height: 50px;
margin: 50px auto;
}
ul li {
width: 50px;
height: 50px;
margin-right: 20px;
float: left;
list-style: none;
}
ul li:first-child {
background: red;
}
ul li:nth-child(2) {
background: green;
}
ul li:nth-child(3) {
background: blue;
}
ul li:nth-child(4) {
background: yellow;
}
ul li:nth-child(5) {
background: pink;
}
</style>
</head>
<body>
<ul id="ul">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script type="text/javascript">
HTMLElement.prototype.__defineGetter__("currentStyle", function() {
return this.ownerDocument.defaultView.getComputedStyle(this, null);
});//兼容性写法,兼容谷歌和火狐,获得非内联样式中的样式值,源自百度,可以自己百度。
var ul = document.getElementById("ul");
var body = document.getElementsByTagName("body")[0];
ul.addEventListener("click", click_btn, false);
function click_btn(event) {
event = event || window.event;
//判断触发时间目标元素的标签名,忽视其他元素点击事件
if (event.target.tagName == 'LI'){
body.style.background = event.target.currentStyle.background;
}
else{
return;
}
} </script>
</body>
</html>
上述代码功能,点击颜色方块,改变body背景色为li标签的背景色。通过事件对象进行判断,得到具体的触发事件的元素,进行相应的事件处理。
时间代理的优点:减少代码量,方便快捷。