JS兼容问题

//1.滚动条到顶端的距离
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

//2.滚动条到左边的距离
  var scrollLeft = document.documentElement.scrollLeft || document.body.ScrollLeft;

//3.byClassName的兼容(通过class获取指定的对象)
  function byClassName(obj,className){
    //判断是否支持byClassName方法
    if(obj.getElementsByClassName){
      //直接使用
      return obj.getElementsByClassName(className);
    }else{//不支持
      //获取所有的标签
      var eles = obj.getElementsByTagName("*");
      var arr = [];
      //获取每一个标签对象
      for(var i = 0,len = eles.length;i < len;i++){
        //判断每一个对象是否具有指定的className
        if(eles[i].className === className){
          arr.push(eles[i]);
        }
      }
      return arr;
    }
  }

//4.获取元素对象中class属性值的兼容
  function getClassValue(obj){
    return obj.getAttribute('class') ? obj.getAttribute('class') : obj.getAttribute('className');
  }

//5.获取非行内样式的兼容
  function getStyle(obj,attr){
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,1)[attr];
  }

//6.获取事件对象的兼容
  evt = evt || window.event;

//7.获取鼠标编码值得兼容
  function getButton(evt){
    var e = evt || window.event;
    if(evt){
      return e.button;
    }else if(window.event){
      switch(e.button){
        case 1 : return 0;
        case 4 : return 1;
        case 2 : return 2;
      }
    }
  }

//8.阻止事件冒泡的兼容
  event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;

//9.获取键盘编码值onkeypress的兼容
  event.keyCode || event.charCode || event.which;

//10.阻止超链接的默认行为的兼容
  event.preventDefault ? event.preventDefault() : event.returnValue = false;

//11.添加事件监听的兼容
  function addEventListener(obj,event,fn,bool){
    if(obj.addEventListener){
      obj.addEventListener(event,fn,bool);
    }else if(obj.attachEvent){
      obj.attachEvent('on' + event,fn);
    }
  }

//12.移除事件监听器的兼容
  function removeEventListener(obj,event,fn, bool){
    if(obj.removeEventListener){
      obj.removeEventListener(event,fn,bool);
    }else if(obj.detachEvent){
      obj.detachEvent('on' + event,fn);
    }
  }

//13.获取事件源的兼容
  var target = event.target || event.srcElement;

//14.创建Ajax(XMLHttpRequest)对象兼容

  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

posted @ 2019-02-26 16:06  元哥0317  阅读(127)  评论(0编辑  收藏  举报