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);}
Prompt when Mouse is released on parent element:
You left the parent element!
You left the child element!
Prompt when Mouse is released on child elements:
You left the parent element!
You left the child element!
Because the MouseUp event is registered on the window, however, I need the effect is, let it be able to have the resolution, when the mouse click on the parent element, the trigger is the parent element matching the content, click on the child element, the trigger is and the child elements matching content.
Reply content:
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);}
Prompt when Mouse is released on parent element:
You left the parent element!
You left the child element!
Prompt when Mouse is released on child elements:
You left the parent element!
You left the child element!
Because the MouseUp event is registered on the window, however, I need the effect is, let it be able to have the resolution, when the mouse click on the parent element, the trigger is the parent element matching the content, click on the child element, the trigger is and the child elements matching content.
window only needs to be bound once to event.target
determine the event trigger.
window.addEventListener('mouseup',function(e){ console.log('你离开了: ' + e.target.id);},false);
The general wording:
p.addEventListener('mousedown',function down(e){ window.addEventListener('mouseup',function up(){ window.removeEventListener('mouseup', up); //p=>up }); //p=>down});