js计算dom间相对视窗位置偏移

项目场景:

  菜单,根据点击的目标,自动调整展示位置

图示:(计算left、top偏移差)

 算法:

/* *
 * 相对偏移值
 * @param target: 计算的目标对象
 * @param reference: 计算的参照物
 * */
 reposition(target, reference) {
     var docH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
         tRect = reference.getBoundingClientRect(),
         mRect = target.getBoundingClientRect();
     /**
      * 根据相对视口的坐标偏移,计算相对位置的偏移量
      *(top偏移:rect的top的坐标偏移差,left偏移:rect的left坐标偏移差)
      **/
      var tTop = tRect.top,
          tLeft = tRect.left,
          mTop = mRect.top,
          mLeft = mRect.left,
          top = target.offsetTop + (tTop - mTop) + tRect.height,
          left = target.offsetLeft + (tLeft - mLeft);
      var offsetD = tRect.y + tRect.height;

      if (docH - offsetD < mRect.height) { // 防止底部空间不够无法展示,有待跟进一步优化
           //top = top - mRect.height - tRect.height;
top -= mRect.height - docH + offsetD; // 上移被隐藏的部分 }
return { left: left, top: top }; }
原文地址:https://www.cnblogs.com/xtreme/p/12553633.html