Event对象跨浏览器兼容性写法

Wmeng0 2019-12-29

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Event对象跨浏览器兼容性写法</title>
</head>
<body>
    <script>
        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]=handler;
                }
            },
            //获取事件本身
            getTarget:function (){
                return event.target || event.srcElement;
            },
            //阻止默认行为
            preventDefault:function (){
                if(event.preventDefault){
                    event.preventDefault();
                }else{
                    event.returnValue=false;
                }
            },
            //取消冒泡和捕获
            stopPropagation:function (){
                if(event.stopPropagation){
                    event.stopPropagation();
                }else{
                    event.cancelBubble=true;
                }
            }
        }
    </script>
    <!-- 测试 -->
    <div id="div">
        爸爸
        <button id="btn">儿子</button>
    </div>
    <a id="a" href="https://www.baidu.com/">百度</a>
    <script>
        var div=document.getElementById("div");
        var btn=document.getElementById("btn");
        EventUtil.addHandler(div,"click",function(){
            console.log("我是老子");
            console.log(EventUtil.getTarget(event));//获取target
        })
        EventUtil.addHandler(btn,"click",function(){
            console.log("我是儿子");
            EventUtil.stopPropagation();//阻止了冒泡
        })
        var a=document.getElementById("a");
        EventUtil.addHandler(a,"click",function(){
            console.log("我是链接");
            EventUtil.preventDefault();//阻止默认行为
        })
    </script>
</body>
</html>

相关推荐