Talk is cheap. Show me your code

计算DOM节点相对于某个特定DOM节点的 offsetTop

问题描述:

页面中有这样的结构:

<main>
  <section>
    <p>long time no see</p>
    <p>long time no see</p>
  </section>
  <table>
    <tr>
      <th>Name</th>
      <th>Info</th>
    </tr>
    <tr>
      <td>Wise</td>
      <td>Wrong</td>
    </tr>
  </table>
</main>

需要获取某个 <td> 相对于 <main> 标签的 offsetTop

如果直接获取 <td> 的 offsetTop,由于 <td> 的 offsetParent 是 <tr>,所以这个值是不准确的,需要另外计算

 

 

解决方案:

按照 DOM 树结构,一级一级的往上找,直到找到 offsetParent 为 <main> 的节点为止

然后将中间节点的 offsetTop 相加,就是最终的 offsetTop

/**
 * 递归计算节点的 offsetTop
 * @param {Element} node      当前节点
 * @param {Element} container 目标节点
 * @param {Number} top        offsetTop
 * @returns Number
 */
function getAbsTop(node, container, top = 0) {
  if (!node || !container) {
    return 0;
  }

  const offsetTop = top + node.offsetTop;

  if (node.offsetParent === container) {
    return offsetTop;
  } else {
    return getAbsTop(node.offsetParent, container, offsetTop);
  }
}

同样的,offsetLeft 也可以按照这个方法来获取

 

posted @ 2021-05-08 16:01  Wise.Wrong  阅读(323)  评论(0编辑  收藏  举报