getBoundingClientRect属性研究

153 阅读1分钟

getBoundingClientRect属性研究

概念

getBoundingClientRect 返回 width、height和下图中的6个属性

element-box-diagram.png

实测总结:

抓住一个核心点,就是height、width的值:

  • box-sizing 是 content-box时,width和height = 内容+border+padding
  • box-sizing是 border-box时, width和height = 我们设置的width、height

所以:

  • top、left很好算,就是元素到左上角原点的距离
  • bottom、right说白了就是在 top/left的基础上 加上 上面说的 height/width
  • 另外一点需要注意的是:当页面有滚动条时,随着滚动条左右上下滚动,top、bottom、left、right都会跟着变;比如原来的top值是0,页面向上滚动了100px,那么top值就成了 -100

代码实测

box-sizing:content-box时

image.png

box-sizing:border-box时

image2.png

有滚动条时

image3.png

注意:

在看源码时,经常看到兼容性IE低版本的写法,了解即可,比如看popper.js源码时:

    /**
     * Get bounding client rect of given element
     * @function
     * @ignore
     * @param {HTMLElement} element
     * @return {Object} client rect
     */
    function getBoundingClientRect(element) {
        var rect = element.getBoundingClientRect();
​
        // whether the IE version is lower than 11
        var isIE = navigator.userAgent.indexOf("MSIE") != -1;
​
        // fix ie document bounding top always 0 bug
        var rectTop = isIE && element.tagName === 'HTML'
            ? -element.scrollTop
            : rect.top;
​
        return {
            left: rect.left,
            top: rectTop,
            right: rect.right,
            bottom: rect.bottom,
            width: rect.right - rect.left,
            height: rect.bottom - rectTop
        };
    }