目录
常用事件
监听器(侦听器)和事件监听程序
### 监听器
on+事件 = callback
### 事件监听程序
添加事件监听程序:addEventListener(event,callback,[useCapture:bool])【回调接受触发事件自身】
移除事件监听程序:removeEventListener(event,remove_callback,[useCapture:bool])
event:事件名称
callback:处理事件的回调函数
useCapture:是否在捕捉过程进行回调处理
remove_callback:要移除事件对应的回调函数
### callback
callback接受一个参数,即触发的事件对象
事件捕获和事件冒泡
### 定性:
是两个完成事件的过程,先捕获再冒泡
### 相关问题:
事件捕获过程阻止传播?
事件冒泡过程阻止传播?
### 解决问题:
## 事件冒泡过程阻止传播
在回调函数中调用evt.stopPropagation(),阻止事件冒泡传播
## 事件捕获过程阻止传播
addEventListener(event,callback,[useCapture:bool]),令useCapture=true,使在捕获过程就执行回调处理;
在回调函数中调用evt.stopPropagation(),阻止事件冒泡传播;
### 测试学习代码
<div class="a" style="background-color: yellow;height: 400px;">
a
<div class="b" style="background-color: pink;height: 200px;">
b
<div class="c" style="background-color: green;height:100px;">
c
</div>
</div>
</div><script>
var a = document.querySelector('.a');
var b = document.querySelector('.b');
var c = document.querySelector('.c');
a.addEventListener('click',function(evt){
console.log('1111,a',evt.target);
// evt.stopPropagation();
},false);
b.onclick = function(evt){
console.log('2222,b',evt.target);
}
c.onclick = function(evt){
console.log('3333,c',evt.target);
// evt.stopPropagation();
}
</script>
事件委托
### 定性:
通过监听父元素事件,并利用event.target,实现处理和控制该事件的所有子元素
### event.target:
event即元素触发的事件对象,而event.target永远指向事件捕获的末尾对应的元素(事件目标对象);
所以我们只需要监听父元素某事件,且此时父元素该事件对象的target属性永远指向“事件目标对象”
### 应用场景:
要对某一元素的所有子元素做同类型事件监听和相同事件处理程序
### 参考代码:
<div class="a" style="background-color: yellow;height: 200px;display: flex;">
<div class="b" style="background-color: red;height: 200px;width: 25%;">one</div>
<div class="b" style="background-color: orange;height: 200px;width: 25%;">two</div>
<div class="b" style="background-color: green;height: 200px;width: 25%;">three</div>
<div class="b" style="background-color: cyan;height: 200px;width: 25%;">four</div>
</div>
<script>
var a = document.querySelector('.a');
a.addEventListener('click',function(evt){
evt.target.style.backgroundColor = `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`;
});
</script>