IScroll5兼容IE修改

水平不到家,无法像js大神那样讲得头头是道。仅做记录,以备后查。

iScroll5是不兼容IE低版本的。为兼容IE低版本(以IE8为例),需做以下工作:

1、事件绑定方式兼容

  众所周知,独特的IE有它自己事件处理的方法attachEvent和detachEvent。IScroll5的事件处理统一使用的是utils中的addEvent和removeEvent。需要使这两个方法的方法实现兼容IE8。最终结果如下:

me.addEvent = function (el, type, fn, capture) {
            if (el.addEventListener) {
                el.addEventListener(type, fn, !!capture);
            } else {
                if (typeof fn === 'object' && fn.handleEvent) {   
                    el.attachEvent('on' + type, function () {
                        fn.handleEvent.call(fn);
                    });
                } else {
                    el.attachEvent('on' + type, fn);
                }
            }
        };

        me.removeEvent = function (el, type, fn, capture) {
            if (el.removeEventListener) {
                el.removeEventListener(type, fn, !!capture);
            } else {
                if (typeof fn === 'object' && fn.handleEvent) {
                    el.detachEvent('on' + type, function () {
                        fn.handleEvent.call(fn);
                    });
                } else {
                    el.detachEvent('on' + type, fn);
                }
            }
        };

  为什么这么写,从http://www.veryhuo.com/a/view/50318.html这篇文章中得知IE9 是 IE 家族中第一个支持 addEventListener + handleEvent 的浏览器,IE9 之前的版本连 addEventListener 也没能支持。所以就不得不添加对fn类型和handleEvent方法的判断。

2、事件传参e的处理

  IE事件捕捉接受的参数e为undefined,所以兼容写法需要在方法体插入首行:e = e || window.event;这样的兼容写法。

3、e.preventDefault()和e.stopPropagation()的兼容写法

  e.preventDefault()的兼容写法:

if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

  stopPropagation()的兼容写法:

if (e.stopPropagation) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}

初次写博,不甚严谨。敬请见谅

原文地址:https://www.cnblogs.com/leo-lpf/p/6202156.html