看如下代码:
html:
<div class='parent'>
<div class='child'></div>
</div>
css:
.parent{width:300px;height:300px;position:fixed;top:0px;left:50px;border:1px solid blue;}
.child{width:50px;height:50px;position:absolute;top:0px;left:0px;border:1px solid green;}
js:
var parent=document.getElementsByClassName('parent')[0];
var child=document.getElementsByClassName('child')[0];
parent.addEventListener('click',function(){
console.log('你触发了父元素上的事件!');
},false);
child.addEventListener('click',function(){
console.log('你触发了子元素上的事件!');
},false);
以上代码:一旦点击子元素,则父元素,子元素上的事件都会触发,可我只要子元素触发!
修改后:
js:
var parent=document.getElementsByClassName('parent')[0];
var child=document.getElementsByClassName('child')[0];
registerParent();
registerChild();
function registerParent(){
parent.addEventListener('click',parentEvent,false);
}
function removeParent(){
parent.removeEventListener('click',parentEvent);
}
function parentEvent(){
console.log('你触发了父元素上的事件!');
}
function registerChild(){
child.addEventListener('click',childEvent,false);
}
function removeChild(){
child.removeEventListener('click',childEvent);
}
function childEvent(){
removeParent();
console.log('你触发了子元素上的事件!');
registerParent();
}
// 点击之后还是父元素,子元素都触发了事件,有没有什么办法能够实现我要的效果:点击子元素,父元素上的事件失效,或者不触发??
不冒泡就可以了。