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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-06 13:52:461746Durchsuche

<code>html:
<div id="p">
  <div id="c"></div>
</div>

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);
}
</code>

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

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

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

回复内容:

<code>html:
<div id="p">
  <div id="c"></div>
</div>

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);
}
</code>

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

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

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

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

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

常规的写法:

<code>p.addEventListener('mousedown',function down(e){
   window.addEventListener('mouseup',function up(){
    window.removeEventListener('mouseup', up);
    //p=>up
  });
    //p=>down
});</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn