jQuery UI Dialog在iframe中的显示位置优化

在使用jQuery UI的Dialog插件时遇到一个问题,就是在iframe中使用时弹出的位置总是偏离屏幕中心,有时有一半被遮住,有时是直接整个页面跳到顶部,关掉Dialog之后又回到原来位置,感觉很突兀。所以写了一个通用顶部距离计算方法,主要功能就是将弹出框位置锁定在当前窗口的中间位置,优化界面的用户体验。

主要思路就是通过获取当前鼠标点击事件、当前屏幕高度、是否在iframe内部以及iframe滚动高度等参数,然后综合计算触发弹出的Dialog距离iframe顶部位置,从而避免iframe页面的来回跳转,直接将弹出位置显示在屏幕中央。

方法源码如下:

function calcDialogTop(screenY, dialog, pos, target) {
  var innerHeight = document != parent.document ? parent.window.innerHeight : window.innerHeight;
  if (typeof innerHeight != 'number') {
    innerHeight = document != parent.document ? (parent.document.documentElement || parent.document.body).clientHeight : (document.documentElement || document.body).clientHeight;
  }

  if (target==undefined) {
    return (pos.top+50);
  } else {
    var offsetY = document != parent.document ? pos.top + $(target).offset().top + innerHeight * 0.5 - screenY : $(target).offset().top + innerHeight * 0.5 - screenY ;
    if ($(dialog).height() < innerHeight * 0.9) {
      return offsetY - $(dialog).height() * 0.3 > 0 ? offsetY - $(dialog).height() * 0.3 : 0;
    } else {
      return offsetY - innerHeight * 0.3 > 0 ? offsetY - innerHeight * 0.3 : 0;
    }
  }
}

使用该方法后的在线演示地址:https://www.techzero.cn/demo/calc-dialog-top/index.html

暂无评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

验证码已失效,请刷新验证码