zoukankan      html  css  js  c++  java
  • 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取消冒泡 }; };

      

  • 相关阅读:
    Linux服务器使用tar加密压缩文件
    ssh-copy-id使用非默认22端口
    Nginx日志分割脚本
    MySQL的yum源
    vSphere Client开启虚拟机提示:出现了常规系统错误: 由于目标计算机积极拒绝,无法连接。
    ESXi主机遗忘密码重置密码
    扩容swap交换分区空间
    ESXi上的固态硬盘识别为非SSD
    VMware Vcenter Server 6.0忘记密码
    Centos6与Centos7区别
  • 原文地址:https://www.cnblogs.com/tangzhirong/p/4816846.html
Copyright © 2011-2022 走看看