当一个子级元素触发事件时,所有父级都会触发相同的事件
例如:小盒子在大盒子内部,点击小盒子就会点到大盒子
注意:
语法:事件对象.target(标准浏览器) 或者 事件对象.srcElement(ie78)
onDiv.addEventListener("click",function(e){
console.log("事件目标:",e.target)
})
语法:dom元素.addEventListener('事件类型',事件处理函数,false/true)
第三个参数不写,默认是false。
false:冒泡;true:捕获。
冒泡:自底向上
被点击元素 => 逐层向上的父级 => document => window
捕获:自顶向下
window => document => 逐层向下的父级 => 被点击元素
第一对:mouseover / mouseout【会冒泡】
第二对:mouseenter / mouseleave【不会冒泡】
一般使用第二对,第一对因为会冒泡事件,所以做判断逻辑上会有一些问题。
sonDiv.onmouseover = function(){
console.log("移入son")
}
sonDiv.onmouseout = function(){
console.log("移出son")
}
fatherDiv.onmouseover = function(){
console.log("移入father")
}
fatherDiv.onmouseout = function(){
console.log("移出father")
}
-----------------
sonDiv.onmouseenter = function(){
console.log("移入son")
}
sonDiv.onmouseleave = function(){
console.log("移出son")
}
fatherDiv.onmouseenter = function(){
console.log("移入father")
}
fatherDiv.onmouseleave = function(){
console.log("移出father")
}
根据事件冒泡原理,将子元素上的事件绑定到父级元素上去完成。
优势:
可以用于给动态生成的标签绑定事件
减少事件绑定次数,提供性能
如果需要靠点击移除img,可以借助window的click事件,当发现事件目标是img,就remove掉。
这个实现思路就是事件委托。
window.onclick = function(e){
var target = e.target;
if(target.className == "img"){
target.remove();
}
}
语法:事件对象.stopPropagation()
ie78:事件对象.cancelBubble = true
这个方法可以阻止冒泡和捕获
事件处理函数里面的this就是事件源
for(var i=0;i<imgS.length;i++){
imgS[i].onclick = function(e){
this.remove();//删除这个imgS[i]元素
}
}
语法:
事件对象.preventDefault()事件对象.returnValue = falsereturn falsea.onclick = function(e){
e.returnValue = false;
}
form.addEventListener("sumbit",function(e){
e.preventDefault();
})
// dom0级
div.oncontextmenu = function(){
return false;
}