JS事件兼容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
    <style>
        #eee{
            width: 100px;
            height: 100px;
            border: 1px solid #eee;
            background-color: pink;
        }
    </style>
<body>
    <div id="eee"></div>
</body>
<script>
        // 事件添加方法 onclick没有兼容问题,ele.onclick=function(){}
        // addEventListener('事件type',function(){})ie>=9才能用 oppera
        // attachEvent ie6-10可用
        // event当前对象也有兼容问题event||window.event(ie的);

        // 1.判断是否有相应的方法然后选择,封装成一个函数可复用
        // 存在问题,每次都调用 怎么解决?判断一次即可,原本返回的是直接执行表达式不能再传参数,再用一个函数包裹返回即可
        // attachEvent回调函数中的this指向window!!
        function selAddEvent(){
            if (window.addEventListener) {
                //这个在ie8要写上window
                return function(target,type,handler){
                    target.addEventListener(type,handler);
                }    
            }else if (window.attachEvent) {
                return function(target,type,handler){
                    target.attachEvent("on"+type,function(e){handler.apply(target,[e]);});
                        // 回调函数传逻辑,apply参数2记得加[];
                    // target.attachEvent("on" + type, function(){
     //                    handler.call(target, window.event);})
                }
            }else{
                return function(target,type,handler){
                    target["on"+type]=handler;
                }
            }
        };
        var ee=document.getElementById('eee');
        var foo=selAddEvent();
        foo(ee,'click', function(j){alert(this);alert(j);});
        // eee.addEventListener('click', function(e){console.log(e)});
</script>
</html>

 

posted @ 2017-04-02 10:28  little_ab  阅读(110)  评论(0)    收藏  举报