首页 > Web开发 > 详细

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

时间:2020-03-23 18:33:57      阅读:113      评论:0      收藏:0      [点我收藏+]

项目场景:

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

 

图示:(计算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 }; }

 

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

原文:https://www.cnblogs.com/xtreme/p/12553633.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!