getBoundingClientRect浅析

309 阅读1分钟

getBoundingClientRect浅析

getBoundingClientRect()获取元素位置,这个方法没有参数

  • 用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。

  • 是DOM元素到浏览器可视范围的距离(不包含文档卷起的部分)

image-20220719172205879.png

看 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
        };
    }

poper.js的基本思路:

  1. 获取reference元素的位置
  2. 根据获取的位置,再计算出popper的位置,定位上去就行了

The End.