2017/12/10 - 元素宽高,位置的兼容性完备处理

2017-12-10  本文已影响0人  YXCoder

之前写代码都会用jquery,元素宽高和位置很容易就能得到。随着浏览器,前端技术的更新换代,jquery开始走下坡路,各大框架纷纷崛起,前端发生翻天覆地的变化,基础JS显得尤为重要。

这里总结一下元素的宽高,视口左边,文档坐标的各浏览器兼容性完备处理。

var win = function(){
      var w = window;
      var width = w.innerWidth;                
      var height = w.innerHeight;
      var outWidth = w.outerWidth;
      var outHeight = w.outerHeight;
}

这里outWidth和outHeight为整个浏览器的宽高,包括工具栏,地址栏等

var offset = function(ele){   //文档位置属性
      var w = window;
      var box = ele.getBoundingClientRect();
      var winHeight = w.innerHeight;
      var winWidth = w.innerWidth;
      var width = box.width || (box.right - box.left);
      var height = box.height || (box.bottom - box.top);
      var top, left, right, bottom;
      top = box.top + this.scroll(ele).scrollY;
      left = box.left + this.scroll(ele).scrollX;
      right = winWidth - box.right;
      bottom = winHeight - box.bottom;
      return {
          width: width,                //文档元素宽度
          height: height,              //文档元素高度
          top: top,                    //元素与文档顶部距离
          left: left,                  //元素与文档左部距离
          right: right,                //元素与文档右部距离
          bottom: bottom               //元素与文档底部距离
       }
    }

这里文档坐标是指元素在整个文档中的位置,就算发生滚动,文档位置也不会变化

var client = function(ele){    //视口位置属性
       var w = window;
       var box = ele.getBoundingClientRect();
       var winHeight = w.innerHeight;
       var winWidth = w.innerWidth;
       var top = box.top;
       var left = box.left;
       var right = winWidth - box.right;
       var bottom = winHeight - box.bottom;
       return {
           top: top,
           left: left,
           right: right,
           bottom: bottom
       }
   }

视口坐标会随着滚动条的变化而变化

scroll = function(){
       var scrollX, scrollY;
       var w = window;
       if(w.pageXOffset != null){
           scrollX = w.pageXOffset;
           scrollY = w.pageYOffset;
       } else if(document.compatMode == 'CSS1Compat'){
           scrollX = d.documentElement.scrollLeft;
           scrollY = d.documentElement.scrollTop;
       } else {
           scrollX = d.body.scrollLeft;
           scrollY = d.body.scrollTop;
       };
       return {
           scrollX: scrollX,
           scrollY: scrollY
       }
   }

这里滚动条做了很多兼容性处理


之前写代码的时候总要去思考元素的各种坐标如何获取,兼容性处理如何做,这里做一个总结,可以加深一点印象

上一篇 下一篇

猜你喜欢

热点阅读