js事件委托和事件代理案例分享
作者:diasa 时间:2024-04-28 09:51:31
什么是事件委托/事件代理
利用事件的冒泡传播机制(触发当前元素的某一个行为,它父级所有元素的相关行为都会被触发),如果一个容器中有很多元素都要绑定点击事件,我们没有必要一个个的绑定了,只需要给最外层容器绑定一个点击事件即可,在这个方法执行的时候,通过事件源的区分来进行不同的操作。
具体小案例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
font-size:14px;
}
html,body{
width:100%;
height:100%;
overflow:hidden;
}
#box{
position:absolute;
left:50%;
top:50px;
width:100px;
height:30px;
margin-left:-50px;
line-height:30px;
text-align:center;
border:1px solid #2489cc;
}
#mark{
position:absolute;
top:30px;
left:-1px;
width:300px;
height:100px;
line-height:100px;
text-align:center;
background:#ffe470;
border:1px solid #2489cc;
}
</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.style.display === "none"
}
</script>
</body>
</html>
标签:js,事件委托,事件代理
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
当前流行的JavaScript代码风格指南
2024-04-22 13:10:08
zookeeper python接口实例详解
2023-03-11 01:34:48
python 获取一个值在某个区间的指定倍数的值方法
2023-04-08 17:19:07
Python实现压缩文件夹与解压缩zip文件的方法
2023-07-31 20:43:09
MySql 5.6.14 Win32位免安装解压缩版配置教程
2024-01-13 01:27:44
Python遍历文件夹和读写文件的实现代码
2023-07-28 12:13:10
![](https://img.aspxhome.com/file/2023/4/60514_0s.jpg)
python之django路由和视图案例教程
2021-06-24 09:48:09
![](https://img.aspxhome.com/file/2023/4/134994_0s.png)
详解python中的线程与线程池
2022-02-02 18:27:19
Access数据库操作中出现的怪现象
2008-04-24 14:22:00
python中用ggplot绘制画图实例讲解
2023-07-04 07:25:16
![](https://img.aspxhome.com/file/2023/1/77041_0s.jpg)
如何利用python实现Simhash算法
2021-06-13 20:12:49
![](https://img.aspxhome.com/file/2023/1/109861_0s.png)
Python WSGI的深入理解
2021-04-20 21:48:25
关于Vue的异步组件
2024-05-09 10:52:35
Python WebSocket长连接心跳与短连接的示例
2022-08-20 04:05:15
Python Flask + Redis 程序练习
2022-07-26 13:49:55
![](https://img.aspxhome.com/file/2023/8/86398_0s.png)
OpenCV角点检测的实现示例
2023-06-25 06:49:10
python openpyxl使用方法详解
2021-12-23 14:49:18
Python使用matplotlib绘制三维参数曲线操作示例
2021-03-30 05:55:31
![](https://img.aspxhome.com/file/2023/6/102776_0s.png)
经典SQL语句大全第1/2页
2024-01-28 09:01:56
python3发送request请求及查看返回结果实例
2023-09-18 11:34:10