javascript---事件对象
事件对象event
如果是事件处理函数绑定的函数,浏览器会默认传递一个参数,event对象。而这个对象会根据触发的事件判断是鼠标事件还是键盘事件
//鼠标事件
1 document.onclick=function(evt){ 2 alert(evt); //键盘事件 3 }
//键盘事件
1 document.onkeydown=function(evt){ 2 alert(evt); //键盘事件 3 }
由于IE浏览器和W3C浏览器获取event对象有不兼容的地方,所以需要兼容方法:
1 var e=evt||window.event;
event对象的属性和方法:
1.可视区坐标(浏览器)
clientX clientY
1 document.onclick=function(evt){ 2 var e=evt||window.event; 3 alert(e.clientX+','+e.clientY); 4 }
2.离屏幕的位置
screenX screenY
1 document.onclick=function(evt){ 2 var e=evt||window.event; 3 alert(e.screenX+','+e.screenY); 4 }
3.获取对应标签名
target
兼容IE写法:
1 function getTarget(evt){ 2 var e=evt||window.event; 3 return e.target||e.srcElement; 4 }
事件流:
事件流包括两种模式:冒泡和捕获,现在浏览器默认情况下都是冒泡模型
冒泡:从里往外逐个触发
捕获:从外往里逐个触发
1 //冒泡 2 document.onclick=function(){ 3 alert('document'); 4 } 5 document.documentElement.onclick=function(){ 6 alert('html'); 7 } 8 document.body.onclick=function(){ 9 alert('body'); 10 } 11 document.getElementById('box').onclick=function(){ 12 alert('box'); 13 }
即当点击box的时候,还会弹出body,html和document,这就是冒泡,我们有时候需要阻止冒泡
取消冒泡:
e.stopPropagation(); //w3c,取消冒泡
e.cancelBubble=true; //IE,取消冒泡
1 //兼容 2 function setStop(evt){ 3 var e=evt||window.event; 4 (typeof e.stopPropagation=='function')?e.stopPropagation():e.cancelBubble=true; 5 }