clientTop,scrollTop,兼容

在开发中常见的额兼容性问题:

scrollTop问题:

function scroll() { // 开始封装自己的scrollTop
  if(window.pageYOffset != null) { // ie9+ 高版本浏览器
    // 因为 window.pageYOffset 默认的是 0 所以这里需要判断
    return {
      left: window.pageXOffset,
      top: window.pageYOffset
    }
  }else if(document.compatMode === "CSS1Compat") { // 标准浏览器 来判断有没有声明DTD
    return {
      left: document.documentElement.scrollLeft,
       top: document.documentElement.scrollTop
    }
  }
    return { // 未声明 DTD
      left: document.body.scrollLeft,
      top: document.body.scrollTop
     }
}

clientTop,clientLeft

/获取屏幕可视区域的宽高
function client(){
  if(window.innerHeight !== undefined){
    return {
      "width": window.innerWidth,
      "height": window.innerHeight
    }
  }else if(document.compatMode === "CSS1Compat"){
    return {
      "width": document.documentElement.clientWidth,
      "height": document.documentElement.clientHeight
    }
  }else{
    return {
      "width": document.body.clientWidth,
      "height": document.body.clientHeight
    }
  }
}

/**
* 获取元素样式兼容写法
* @param ele
* @param attr
* @returns {*}
*/
function getStyle(ele,attr){
  if(window.getComputedStyle){
    return window.getComputedStyle(ele,null)[attr];
  }
  return ele.currentStyle[attr];
}

posted @ 2017-12-12 14:21  仙人掌的成长  阅读(163)  评论(0编辑  收藏  举报