js 添加事件兼容性

时间:2021-04-08 04:37:58
        var tools = {
            //添加事件
            addHandle: function (e, type, handle) {
                if (e.addEventListener) {
                    e.addEventListener(type, handle, false);
                } else if (e.attachEvent) {
                    e.attachEvent("on" + type, handle);
                }
                else {
                    e["on" + type] = handle;
                }
            },
            //删除事件
            removeHandle: function (e, type, handle) {
                if (e.addEventListener) {
                    e.removeEventListener(type, handle, false);
                } else if (e.attachEvent) {
                    e.detachEvent("on" + type, handle);
                }
                else {
                    e["on" + type] = null;
                }
            },
            //得到对象
            getEvent: function (event) {
                return event || window.event;
            },
            //得到元素
            getElement:function(event){
                return event.target||event.srcElement;
            },
            //阻止冒泡
            stopPropagation: function (event) {
                if (event.stopPropagation) {
                    event.stopPropagation();
                } else {
                    event.cancelBubble = true;
                }
            },
            //阻止默认行为
            preventDefault: function (event) {
                if (event.preventDefault) {
                    event.preventDefault();
                } else {
                    event.returnValue = false;
                }
            }
        }

        var btn = document.getElementById("btn");
        var box = document.getElementById("box");
        var ha = document.getElementById("ha");

        tools.addHandle(ha, "click", function (e) {
            e = tools.getEvent(e);
            tools.preventDefault(e);
            tools.stopPropagation(e);
        })