Javascript事件对象

1.在W3C标准中,获取event对象方法如下:

input.onclick=function(evt){

    alert(evt);
  }

  

2.IE直接用window.event获取。所以常用如下兼容:

input.onclick=function(evt){

  var e=evt||window.event;

    alert(e);

 }

  

3.W3C(非IE)事件的button属性

window.onmouseup=function(evt){

  var e=evt||window.event;

    alert(e.button);  //012分别表示左中右键

 }

  PS:学会编写跨浏览器兼容函数。

4.修改键

window.onload=function(){
  document.onclick=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.onload=function(){
  document.onkeydown=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.onclick=function(){
        alert('document');
    };
    document.documentElement.onclick=function(){
        alert('html');
    };
    document.body.onclick=function(){
        alert('body');
    };
    documnet.getElementById('box').onclick=function(){
        alert('div');
    };
    document.getElementByTagName('input')[0].onclick=function(evt){
        alert('input');
        var e=evt||window.event;
        e.stopPropagation();   //非IE取消冒泡,若无此句,则会从input输出到docement
     e.cancelBubble=true; //IE取消冒泡 }; };

  

原文地址:https://www.cnblogs.com/tangzhirong/p/4816846.html