1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <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 上,但是,我需要的效果是,让其能够有分辨力,当鼠标点击的是父元素时,触发的便是和父元素配套的内容,点击子元素时,触发的便是和子元素配套的内容。
回复内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <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
来判断事件触发者。
1 2 3 | <code>window.addEventListener( 'mouseup' , function (e){
console.log( '你离开了: ' + e.target.id);
},false);</code>
|
登入後複製
常规的写法:
1 2 3 4 5 6 7 | <code>p.addEventListener( 'mousedown' , function down(e){
window.addEventListener( 'mouseup' , function up(){
window.removeEventListener( 'mouseup' , up);
});
});</code>
|
登入後複製