zoukankan      html  css  js  c++  java
  • 基本event封装:阻止冒泡、默认事件等

    <!DOCTYPE html>
    <html>
    <head>
       <meta charset="UTF-8">
    </head>             
    <body>
      <div id="box">
       <input type="button" value="按钮3" id="btn3">
       <a href="http://www.sogou.com/sie?hdq=AQxRG-7004&query=addEventListener%20of%20undefined&p=99350103&oq=&ri=-2" id="go">跳转</a>
      </div>
       <script type="text/javascript">
       var btn3 = document.getElementById('btn3');
       var box = document.getElementById('box');
       var id = document.getElementById('id');
       function showMes(event) {
          event = event || window.event;  //在IE8之前要用的是window.event;
    	  var ele = event.target || event.srcElement; //在IE8之前用的不是target而是srcElement
          alert(ele.nodeName);
    	  event.stopPropagation();
       }
          function showM() {
          alert("RGE");
       }
       function stopGo(event) {
         event.stopPropagation();
    	 event.preventDefault();
       }
    var eventUtil = {
      //给元素添加事件
       addHandler: function(element, type, handler) {
         if(element.addEventListener) {
    	    element.addEventListener(type,handler,false);
    	 } else if(element.attachEvent) {
    	    element.attachEvent('on'+type, handler);
    	 } else {
    	    element['on'+type] = handler;
    	 }
       },
       //给元素删除事件
         removeHandler: function(element, type, handler) {
         if(element.removeEventListener) {
    	    element.removeEventListener(type,handler,false);
    	 } else if(element.detachEvent) {
    	    element.detachEvent('on'+type, handler);
    	 } else {
    	    element['on'+type] = null;
    	 }
       },
       //获得兼容浏览器的事件对象
       getEvent: function(event) {
         return event?event:window.event;
       },
       //获取事件类型
       getType: function(event) {
          return event.type;
       },
       //获取时间来自哪个元素
       getElement: function(event) {
          return event.target || event.srcElement;
       },
       //阻止取消事件的默认行为
       preventDefault:function(event) {
         if(event.preventDefault) {
    	    event.preventDefault();
    	 } else {
    	    event.returnValue = false;
    	 }
       },
       //阻止时间冒泡
       stopPropagation: function(event) {
         if(event.stopPropagation) {
    	     event.stopPropagation();
    	 } else {
    	    event.cancelBubble = true;
    	 }
       }
    }
    eventUtil.addHandler(btn3, 'click', showMes);
    eventUtil.addHandler(box, 'click', showM);
    eventUtil.addHandler(go, 'click', stopGo);
    </script>
    </body>
    </html>
    

      把每一个事件封装在对象里面,把每一个功能封装在方法里面

  • 相关阅读:
    Windows 08 R2_组策略
    Nginx常用配置实例(4)
    Nginx日常维护操作(3)
    Nginx配置文件(2)
    Nginx概述和安装(1)
    Zabbix实战-简易教程--通过公众平台企业号发送短信
    HDFS ZKFC自动切换原理分析
    HDFS ZKFC自动切换原理分析
    DataNode启动优化改进:磁盘检测并行化
    DataNode启动优化改进:磁盘检测并行化
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4121165.html
Copyright © 2011-2022 走看看