Sort out several commonly used compatibility of JavaScript

Sort out several commonly used compatibility of JavaScript

1. Get non-inline styles (compatibility issues) styles (compatibility issues)

function getStyle(obj,attr){    //获取非行间样式,obj是对象,attr是值
   if(obj.currentStyle){       //针对ie获取非行间样式
       return obj.currentStyle[attr];
   }else{
       return getComputedStyle(obj,false)[attr];   //针对非ie
   };
}

2. Get the vertical distance that the scroll bar moves

var _top = null;
    window.onscroll = function(){
        //兼容问题  获取滚动条移动的垂直距离
        _top = document.body.scrollTop || document.documentElement.scrollTop;
        console.log(_top);
    }
    function fun(){
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    }

3. Compatibility of event objects : var e = evt || event;
4. Compatible writing method for keyboard detection

var key = e.keyCode || e.which || e.charCode;

5. Compatibility to prevent bubbling

 e.stopPropagation();
e.stopPropagation ? e.stopPropagation():e.cancelBubble = true;

6. Prevent browser default events

e.preventDefault?e.preventDefault():e.returnValue = false;
return  false;

7. Event monitoring compatibility

 function addEvent(obj,type,callBack){
        if(obj.addEventListener){//非IE版本
            obj.addEventListener(type,callBack);
        }else{//IE版本
            obj.attachEvent("on"+type,callBack);
        }
    }
    addEvent(document,"click",function(){alert("document")});

Guess you like

Origin blog.csdn.net/qq_43923146/article/details/107705655