如何获取任一层级的dom元素到指定上层dom的left、top属性?

结构如下:

<div class="wrapper" id="wrapper">
    <div id="node-root">
        <div id="node-2">
            <div id="node-3"></div>
            <div id="node-3-1"></div>
            <div id="node-3-2"></div>
        </div>
        <div id="node-22">
            <div id="node-22-1"></div>
        </div>
        <div id="node-33">
            <div id="node-33-1"></div>
        </div>
    </div>
</div>

请问节点id="node-root"及其所有子(孙)节点,如何获取到节点id="wrapper"的left、top属性?

阅读 965
2 个回答
/**
 * 获取元素距浏览器最顶部及最左边的距离
 * @param ele dom元素
 * @returns {{top: number, left: number}}
 */
function offset (ele) {
  var positon = {
    top: 0,
    left: 0
  };
  if (!ele || ele.nodeType != 1) {
    return positon;
  }
  var offsetParent = ele.offsetParent;
  positon.top = ele.offsetTop;
  positon.left = ele.offsetLeft;
  while (offsetParent != null) {
    positon.top += offsetParent.offsetTop;
    positon.left += offsetParent.offsetLeft;
    offsetParent = offsetParent.offsetParent;
  }
  return positon;
}

/**
 * 获取元素距指定父级元素最顶部及最左边的距离
 * @param ele dom元素
 * @param boundaryParent 边界父级元素,默认为null
 * @returns {{top: number, left: number}}
 */
function offsetInParent (ele, boundaryParent) {
  var positon = {
    top: 0,
    left: 0
  };
  var elOffset = offset(ele);
  var parentOffset = {
    top: 0,
    left: 0
  };
  if (boundaryParent) {
    parentOffset = offset(boundaryParent);
  }
  positon.top = elOffset.top - parentOffset.top;
  positon.left = elOffset.left - parentOffset.left;
  return positon;
}

// 调用
console.log(offsetInParent(document.getElement('node-22-1'), document.getElement('wrapper')))

从父级开始遍历,匹配子元素

推荐问题
宣传栏