• 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取消冒泡 }; };

      

  • 相关阅读:
    redhat下设置网桥br0
    RackSpace推开源云计算平台OpenStack震动业界
    centos5.2 64位yum国内源之首选 上海交大(未验证)
    image config
    编程的四种境界
    怎样学好C语言
    利用SSL加密HTTP通道加强IIS安全性
    Sql Server 日期函数
    如何启用Oracle 11g的默认用户Scott
    ASP.NET自定义错误处理页面的添加
  • 原文地址:https://www.cnblogs.com/tangzhirong/p/4816846.html
Copyright © 2020-2023  润新知