1.在W3C标准中,获取event对象方法如下:
input.οnclick=function(evt){
alert(evt);
}
2.IE直接用window.event获取。所以常用如下兼容:
input.οnclick=function(evt){
var e=evt||window.event;
alert(e);
}
3.W3C(非IE)事件的button属性
window.οnmοuseup=function(evt){
var e=evt||window.event;
alert(e.button); //012分别表示左中右键
}
PS:学会编写跨浏览器兼容函数。
4.修改键
window.οnlοad=function(){
document.οnclick=function(evt){
alert(getKey(evt));
}
function getKey(evt){
var e=evt||window.event;
var keys=[];
if(e.shiftKey) keys.push('shift');
if(e.ctrlKey) keys.push('ctrl');
if(e.altKey) keys.push('alt');
return keys;
}
5.keyCode返回键码
window.οnlοad=function(){
document.οnkeydοwn=function(evt){
alert(evt.keyCode);
}
PS:如果用keypress返回keyCode,返回Firefox浏览器把所有字符键返回0。
但Chrome、IE浏览器都支持keypress返回keyCode,还支持大小写。
6.charCode返回字符编码
7.target(非IE)、srcElement(IE)返回点击的DOM元素对象。
return e.target||e.srcElement;
8.事件冒泡
从内层元素逐渐想顶层冒泡输出。
window.onlaod=function(){
document.οnclick=function(){
alert('document');
};
document.documentElement.οnclick=function(){
alert('html');
};
document.body.οnclick=function(){
alert('body');
};
documnet.getElementById('box').οnclick=function(){
alert('div');
};
document.getElementByTagName('input')[0].οnclick=function(evt){
alert('input');
var e=evt||window.event;
e.stopPropagation(); //非IE取消冒泡,若无此句,则会从input输出到docement
e.cancelBubble=true; //IE取消冒泡
};
};