当面试官问:‘如何获取文档中任意一个元素与文档顶部的距离?’

jQuery  offset方法实现

用于对于设置匹配元素相对于文档的偏移。返回的对象包含两个整型属性:top和left;

手动实现jQuery offset方法 解决思路有两种:

1.通过递归实现

DOM元素有一个属性是someElement.offsetTop,表示该元素到父元素顶部的距离。所以最后的答案就是递归将所有的offsetTop加起来。

/** 定位到某元素顶部 **/
function getElementToPageTop(el) {
  if(el.parentElement) {
    return this.getElementToPageTop(el.parentElement) + el.offsetTop
  }
  return el.offsetTop
}

2.通过getBoundingClientRect方法实现。

此方法是用来描述一个DOM元素的具体位置,改位置下面的4个属性都是相对左上角而言的。

function getBoundingClientRect(obj) {
    var boundingClientRect = obj.getBoundingClientRect();
    var newObj = {
        bottom: boundingClientRect.bottom,
        left: boundingClientRect.left,
        right: boundingClientRect.right,
        top: boundingClientRect.top
    }

    if (boundingClientRect.width) {
        newObj.width = boundingClientRect.width;
        newObj.height = boundingClientRect.height;
    } else {
        newObj.width = boundingClientRect.right - boundingClientRect.left;
        newObj.height = boundingClientRect.bottom - boundingClientRect.top;
    }
    return newObj;
}

 

posted @ 2022-03-10 09:43  小十六哇  阅读(277)  评论(0编辑  收藏  举报