zoukankan      html  css  js  c++  java
  • js事件兼容处理

    js封装事件处理函数,兼容ie,支持事件代理

    var eventUtil = {
        bindEvent: function(el, type, target, callback, popgation) {
            /**
             * @author zhangtian
             * @date 2017/11/16
             * @desc 标准浏览器与ie事件兼容处理
             * @augments el:事件源 type事件类型 target事件代理元素 callback回调函数 popgation是否冒泡
             */
            var caption = caption || true; //默认为冒泡
    
            //如果不使用事件代理,target置空
            if((typeof target) == "function") {
                callback = target;
                target = null;
            }
    
            if(el.addEventListener) {
                el.addEventListener(type, function(e) {
                    if(target) {
                        console.log("事件代理");
                        if(e.target == target) {
                            callback.call(target, e); //改变this指向,如果不用call,this指向window
                        }
                    } else {
                        console.log("普通事件");
                        callback.call(el, e); //改变this指向,如果不用call,this指向window
                    }
                }, popgation);
            } else if(el.attachEvent) {
                el.attachEvent("on" + type, function() {
                    var e = window.event;
                    if(target) {
                        console.log("事件代理");
                        if(e.srcElement == target) {
                            callback.call(target, e); //改变this指向,如果不用call,this指向window
                        }
                    } else {
                        console.log("普通事件");
                        callback.call(el, e); //改变this指向,如果不用call,this指向window
                    }
                });
            }
        },
        stopPropagation: function(e) {
            var event = e || window.event;
            if(event.stopPropagation) {
                event.stopPropagation();
            } else {
                event.cancelBubble = true;
            }
        },
        preventDefault: function(e) {
            var event = e || window.event;
            if(event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
        }
    };
    前端发展速度之快,只有不断的学习积累,才能紧跟时代的步伐。
  • 相关阅读:
    正向代理与反向代理的区别
    php返回数据格式化类
    RewriteCond和13个mod_rewrite应用举例Apache伪静态
    sh cssupdate
    JS小游戏仙剑翻牌
    sh cssupdate 优化
    Apache rewrite
    php XML文件解释类
    memcached 常用命令及使用说明
    Apache 搭建虚拟主机
  • 原文地址:https://www.cnblogs.com/zt123123/p/7843567.html
Copyright © 2011-2022 走看看