用过jQuery的offset()的同学都知道

offset().top或offset().left很方便地取得元素相对于整个页面的偏移。

 

而在js里,没有这样直接的方法,节点的属性offsetTop可以获得该节点相对于父节点的相对偏移

但不能直接获得其绝对偏移,我们可用节点逐层递归向上来相加offsetTop来获得绝对偏移。

function getOffset(Node, offset) {
    if (!offset) {
        offset = {};
        offset.top = 0;
        offset.left = 0;
    }

    if (Node == document.body) {//当该节点为body节点时,结束递归
        return offset;
    }

    offset.top += Node.offsetTop;
    offset.left += Node.offsetLeft;

    return getOffset(Node.parentNode, offset);//向上累加offset里的值
}

 

使用时,则如:

var a = document.getElementById('a');
//getOffset(a).top
//getOffset(a).left

 

相关文章:

  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
相关资源
相似解决方案