-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
什么是事件委托/事件代理:
<style>
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
#outer{
margin: 20px auto;
padding: 20px;
width: 300px;
height: 300px;
background: green;
}
#inner{
padding: 20px;
width: 200px;
height: 200px;
background: red;
}
#center{
width: 100px;
height: 100px;
background: pink;
}
</style>
<div id="outer">
<div id="inner">
<div id="center"></div>
</div>
</div>
<script>
var outer = document.getElementById('outer');
var inner = document.getElementById('inner');
var center = document.getElementById('center');
document.body.onclick = function (e) {
e = e || window.event;
//console.log(e.target || e.srcElement);
console.log(e.target.id);
}
</script>
总结:
事件委托就是,利用事件的冒泡传播机制(触发当前元素的某个行为,它父级所有元素的相关行为都会被触发),如果一个容器中很多元素都要绑定点击事件,我们没有必要一个个的绑定,只需要给最外层的容器绑定一个点击事件即可,在这个方法执行的时候,通过事件源的区分来进行不同的操作。
案例:
<style>
body,div,span{
margin: 0;
padding: 0;
font-size: 14px;
}
html,body{
width: 100%;
height: 100%;
overflow: hidden;
}
#box{
position: absolute;
left: 50%;
top: 50px;
margin-left: -50px;
width: 100px;
height: 30px;
border: 1px solid #f60;
text-align: center;
line-height: 30px;
}
#mark{
position: absolute;
top: 30px;
left: -1px;
width: 300px;
height: 100px;
line-height: 100px;
text-align: center;
background: pink;
border: 1px solid #f60;
}
</style>
</head>
<body>
<div id="box">
<span>购物车</span>
<div id="mark" style="display: none;">查看购物车中的详细信息</div>
</div>
<script>
var mark = document.getElementById('mark');
document.body.onclick = function (e) {
e = e || window.event;
e.target = e.target || e.srcElement;
//如果点击的是#box或者是#box下的span,我们判断mark是否显示,显示的话,让其隐藏,反之隐藏的话让他显示
if (e.target.id === "box" || (e.target.tagName.toLowerCase() === "span" && e.target.parentNode.id === "box")) {
if (mark.style.display === "none") {
mark.style.display === "block";
} else {
mark.style.display === "none";
}
return;
}
//如果事件源是#mark,不进行任何的操作
if (e.target.id === "mark") {
return;
}
//以上都不是的话,我们直接让#mark隐藏
mark.style.display === "none";
};
</script>
Metadata
Metadata
Assignees
Labels
No labels