js原生-事件,获取dom兼容写法

获取事件对象的兼容性写法

var obox = document.querySelector(".box");
obox.onclick = function(eve){
    var e = eve || window.event;
}

IE支持:window.event

获取键盘按键值的兼容性写法

var obox = document.querySelector(".box");
obox.onclick = function(eve){
    var e = eve || window.event;
    var code = e.keyCode || e.which;
}

“阻止浏览器默认行为的”兼容性写法

function stopDefault(e){
    if(e.preventDefault)    e.preventDefault();//兼容其他浏览器
    else    e.returnValue = false;//兼容IE
}

“事件冒泡”的兼容写法

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

“添加事件监听器”兼容性写法

function addEvent(ele,type,callback){
    if(ele.attachEvent) ele.attachEvent("on"+type,callback);
    else    ele.addEventListener(type,callback);
}

“删除事件监听器”兼容性写法

function removeEvent(ele,type,callback){
    if(ele.detachEvent) ele.detachEvent("on"+type,callback);
    else    ele.removeEventListener(type,callback);
}

event.target的兼容问题

 otable.onclick = function(eve){
        var e = eve || window.event;
        var target = e.target || e.srcElement;//只看这行
        if(target.nodeName === "TD"){
            var ipt = document.createElement("input");
            ipt.value = target.innerHTML;
            target.innerHTML = "";
            target.appendChild(ipt);
            ipt.focus();

            var that = target;
            ipt.onblur = function(){
                that.innerHTML = this.value;
            }
            ipt.onclick = function(eve){
                var e = eve || window.event;
                e.stopPropagation();
            }
        }
    }

“获取样式”的兼容写法

function getStyle(ele,attr){
    if(ele.currentStyle){//判断获取到的是不是true,那么就执行IE的currentStyle,如果是undefined那么就是false,那就执行getComputedStyle()
        return ele.currentStyle[attr];//IE8及以下支持
    }else{
        return getComputedStyle(ele,false)[attr];//其他正常浏览器支持
    }
}