js中常见的兼容问题

1. 非行内样式获取

高级浏览器:

getComputedStyle(obox.false)//获取所有属性

IE浏览器

obox.currentStyle//获取所有属性

兼容写法

 function getStyle(ele,attr){//ele为获取元素,attr为属性。
        var a = "";
        if(ele.currentStyle){
            a = ele.currentStyle[attr];
        }else{
            a = getComputedStyle(ele,false)[attr];
        }
        return a;
    }

2.事件对象的兼容

 var e=eve||window.event

3.事件源的兼容

e.target||e.srcElement

4.事件冒泡的兼容

高级浏览器

e.stopPropagation()

IE

e.cancelBubble = true;

兼容写法

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

5.获取键盘按下的值

var code = e.keyCode||e.which

6.阻止默认事件

高级浏览器

e.preventDefault()

IE

e.returnValue = false

兼容写法

 function stopDefault(e){
        if(e.preventDefault){
            e.preventDefault()
        }else{
            e.returnValue = false;  
        }
  }

7.DOM2级事件绑定

高级浏览器

obox.addEventListener("click",fn)

IE

obox.attachEvent("onclick",fn)

兼容写法

//绑定兼容写法
addEvent(obox,"click",fn1) function fn1(){ console.log(1) } function addEvent(ele,type,cb){ if(ele.addEventListener){ ele.addEventListener(type,cb) }else if(ele.attachEvent){ ele.attachEvent("on"+type,cb) }else{ ele["on"+type] = cb; } }
 //删除的兼容
removeEvent(obox,"click",fn1)
   function removeEvent(ele,type,cb){
       if(ele.removeEventListener){
           ele.removeEventListener(type,cb)
       }else if(ele.detachEvent){
           ele.detachEvent("on"+type,cb)
       } else{ele["on"+type] = null;
       }
   }

8.window对象的属性:

window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth//可视区域的宽度:

window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight//可视区域的高度度:

document.documentElement.scrollTop || document.body.scrollTop//页面滚动条距离顶部的距离:

document.docimentElement.scrollLeft || document.body.scroll Left//页面滚动条距离左边的距离:

猜你喜欢

转载自www.cnblogs.com/zl-light/p/11756792.html