处理事件的兼容写法

事件绑定兼容写法:

  1.普通写法

<!doctype html>
<title>javascript事件兼容写法</title>
<meta charset="utf-8"/>
<script type="text/javascript">
    var addEvent = function(element,type,callback){
        if(element.addEventListener){
            element.addEventListener(type,callback,false);
        }else if(element.attachEvent){
            element.attachEvent('on' + type,callback)
        }
        
    } 
    
    window.onload = function(){
        addEvent(document.getElementById('parent'),'click',function(event){
            var event = event || window.event;
            var target = event.target || event.srcElement;
            if(target.nodeName.toLowerCase() == 'li'){
                alert(target.id);
            }
        });
    }
</script>
<ul id="parent">
    <li id="test1">aaaa</li>
    <li id="test2">aaaa</li>
    <li id="test3">aaaa</li>
    <li id="test4">aaaa</li>
    <li id="test5">aaaa</li>
    <li id="test6">aaaa</li>
</ul>

 

  2.还可以用闭包的形式来实现

<!doctype html>
<title>javascript事件兼容写法</title>
<meta charset="utf-8"/>
<script type="text/javascript">
    var addEvent = (function(){
        if(document.addEventListener){
            return function(element, type,callback){
                element.addEventListener(type,callback,false);
            }
        }else{
            return function(element, type,callback){
                element.attachEvent('on' + type,callback);
            }
        }
    })();
    window.onload = function(){
        addEvent(document.getElementById('parent'),'click',function(event){
            var event = event || window.event;
            var target = event.target || event.srcElement;
            if(target.nodeName.toLowerCase() == 'li'){
                alert(target.id);
            }
        });
    }
</script>
<ul id="parent">
    <li id="test1">aaaa</li>
    <li id="test2">aaaa</li>
    <li id="test3">aaaa</li>
    <li id="test4">aaaa</li>
    <li id="test5">aaaa</li>
    <li id="test6">aaaa</li>
</ul>

事件移除兼容写法:

  removeEvent()是用来移除addEventLIstener()的,detachEvent()是用来移除ie8以下attachEvent()事件的。

  注:要使用removeEvent(detachEvent)移除事件时,addEventLIstener(attachEvent )的执行函数必须使用外部函数,否则无法移除事件

<!doctype html>
<title>javascript事件兼容写法</title>
<meta charset="utf-8"/>
<script type="text/javascript">
    var addEvent = (function(){
        if(document.addEventListener){
            return function(element, type,callback){
                element.addEventListener(type,callback,false);
            }
        }else{
            return function(element, type,callback){
                element.attachEvent('on' + type,callback);
            }
        }
    })();
    var removeEvent = function(element, type, callback){
        if(element.removeEventListener){
            element.removeEventListener(type,callback,false);
        }else if(element.detachEvent){
            element.detachEvent('on' + type,callback);
        }
    }
    window.onload = function(){
     //因为涉及到移除事件,所以事件的执行函数需要使用外部函数
var myCallback = function(event){ var event = event || window.event; var target = event.target || event.srcElement; if(target.nodeName.toLowerCase() == 'li'){ alert(target.id); } } addEvent(document.getElementById('parent'),'click',myCallback); removeEvent(document.getElementById('parent'),'click',myCallback); } </script> <ul id="parent"> <li id="test1">aaaa</li> <li id="test2">aaaa</li> <li id="test3">aaaa</li> <li id="test4">aaaa</li> <li id="test5">aaaa</li> <li id="test6">aaaa</li> </ul>

 

获取事件源兼容写法:

var getEvent = function(event){
    event = event || window.event;
    return event.target || event.srcElement;
}

阻止冒泡事件:

var stopPropagation = function(event){
     if(event.stopPropagation){
         event.stopPropagation();
     }else{
        event.cancelBubble = true;
     }
 }

阻止默认事件:

var preventDefault = function(){
     if(event.preventDefault){
         event.preventDefault();
     }else{
         event.returnValue = false;
     }
 }

 通用的事件监听函数:  

var Event = {
        addEvent: function(element,type,callback){
            if(element.addEventListener){
                element.addEventListener(type,callback,false);
            }else if(element.attachEvent){
                element.attachEvent('on' + type,callback);
            }
        },
        removeEvent: function(element,type,callback){
            if(element.removeEventListener){
                element.removeEventListener(type,callback,false);
            }else{
                element.detachEvent('on' + type, callback);
            }
        },
        getEvent: function(event){
            return event || window.event;
        },
        getTarget: function(event){
            return event.target || event.srcElement;
        },
        stopPropagation: function(event){
            if(event.stopPropagation){
                event.stopPropagation();
            }else{
                event.cancelBubble = true;
            }
        },
        preventDefault: function(event){
            if(event.prevenDefault){
                event.preventDefault();
            }else{
                event.returnValue = false;
            }
        }
    }

面试题目:写一个通用的事件绑定函数(包括不同绑定和代理绑定),不用考虑IE浏览器

/**
 * 通用事件绑定
 */
function bindEvent(element,type,selector,fn){
    if( typeof fn !== 'function'){ // 这种情况是普通绑定
        fn = selector
        selector = null
    }
    element.addEventListener(type,function(event){
        const target = event.target
        if(selector){ //代理绑定
            //target.matches(selector) 方法接受一个字符串参数 selector,该字符串表示一个CSS选择器。如果目标元素匹配该选择器,则返回 true;否则返回 false
            if(target.matches(selector)){
                //判断符合条件后执行函数
                fn.call(target,event)
            }
        }else{ //普通绑定
            fn.call(target,event)
        }
    })
}

用法:

//普通按钮事件绑定
const btn1 = document.getElementById('btn')
bindEvent(btn1,'click',function(event){
    console.log(event,'event')
    event.preventDefault(); // 阻止默认行为
    event.stopPropagation() //阻止冒泡
    
})

//事件代理
bindEvent(list,'click','.item',function(event){
    console.log(event)
    event.preventDefault(); // 阻止默认行为
    event.stopPropagation() //阻止冒泡
})

 

posted @ 2016-07-06 11:48  yangkangkang  阅读(4225)  评论(0编辑  收藏  举报