欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

javascript - addEventListener注册了多个相同事件,如何让其中一个触发,其他的失效??

程序员文章站 2024-02-04 09:44:34
...
html:
css: #p {width:300px;height:300px;border:1px solid blue;} #c {width:30px;height:30px;background-color:red;} js: var p=document.getElementById('p'); var c=document.getElementById('c'); registerParentEvent(); registerChildEvent(); // 注册父元素事件 function registerParentEvent(){ p.addEventListener('mousedown',function(e){ e.stopPropagation(); console.log('你点击了父元素'); },false); window.addEventListener('mouseup',function(){ console.log('你离开了父元素!'); },false); } // 注册子元素事件 function registerChildEvent(){ c.addEventListener('mousedown',function(e){ e.stopPropagation(); console.log('你点击了子元素'); },false); window.addEventListener('mouseup',function(){ console.log('你离开了子元素!'); },false); }

在父元素上鼠标松开后提示:
你离开了父元素!
你离开了子元素!

在子元素上鼠标松开后提示:
你离开了父元素!
你离开了子元素!

由于 mouseup 事件注册在 window 上,但是,我需要的效果是,让其能够有分辨力,当鼠标点击的是父元素时,触发的便是和父元素配套的内容,点击子元素时,触发的便是和子元素配套的内容。

回复内容:

html:
css: #p {width:300px;height:300px;border:1px solid blue;} #c {width:30px;height:30px;background-color:red;} js: var p=document.getElementById('p'); var c=document.getElementById('c'); registerParentEvent(); registerChildEvent(); // 注册父元素事件 function registerParentEvent(){ p.addEventListener('mousedown',function(e){ e.stopPropagation(); console.log('你点击了父元素'); },false); window.addEventListener('mouseup',function(){ console.log('你离开了父元素!'); },false); } // 注册子元素事件 function registerChildEvent(){ c.addEventListener('mousedown',function(e){ e.stopPropagation(); console.log('你点击了子元素'); },false); window.addEventListener('mouseup',function(){ console.log('你离开了子元素!'); },false); }

在父元素上鼠标松开后提示:
你离开了父元素!
你离开了子元素!

在子元素上鼠标松开后提示:
你离开了父元素!
你离开了子元素!

由于 mouseup 事件注册在 window 上,但是,我需要的效果是,让其能够有分辨力,当鼠标点击的是父元素时,触发的便是和父元素配套的内容,点击子元素时,触发的便是和子元素配套的内容。

window 只需要绑定一次即可,通过 event.target 来判断事件触发者。

window.addEventListener('mouseup',function(e){
    console.log('你离开了: ' + e.target.id);
},false);

常规的写法:

p.addEventListener('mousedown',function down(e){
   window.addEventListener('mouseup',function up(){
    window.removeEventListener('mouseup', up);
    //p=>up
  });
    //p=>down
});