【问题标题】:Why won't my modal open in the dead center of the window?为什么我的模态不会在窗口的死点打开?
【发布时间】:2012-02-10 11:11:21
【问题描述】:

我遇到了一个错误,我的模式无法在中心窗口中打开。我目前用来测量中间的代码如下:

var id = j('#share-modal');

// show modal, resize
j(id).css('top',  j(window).height()/2-j(id).height()/2);                 
j(id).css('left', j(window).width()/2-j(id).width()/2);

j('#share-modal').fadeIn(500);


 CSS

#share-modal {
    display: none;
    font-family: Arial, sans-serif;
    width: 537px;
    height: 510px;
    position: absolute;
    background: #FFF;
    z-index: 100;
    box-shadow: 3px 3px 3px #333;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
}

这是我放置的唯一应该使代码居中的代码,但我不知道是否有其他东西在干扰。

在此处查看我的 Javascript: http://pastebin.com/wZeY5azT

您可以在这里查看:www.paultibbs.com/varier

向下滚动并点击“与朋友分享”按钮。

如果有人能帮我解决这个错误,我将不胜感激!

【问题讨论】:

  • 首先,为什么使用 j 而不是约定俗成的 $? ;-) 它实际上在窗口的死点(如果你一直向上滚动那个页面,你会明白我的意思)。您真正想要的是文档当前显示区域的中心。因此,使用相对于单击事件或按钮所在位置的 y 轴位置。
  • @UstamanSangat 如何对现有答案进行投票,而不是仅仅重复 6 分钟前所说的话?
  • 在这种特定情况下您不必担心它,但请记住,如果您的模态框上有边框、边距或填充,您必须在定位时对其进行补偿,或使用box-sizing: border-box;
  • @thenetimp,当我开始写答案时,没有人可以投票,相信我看看我的时间戳。 :-(

标签: javascript jquery ajax modal-dialog


【解决方案1】:

来自 jQuery 文档:

var height = $(window).height();
var scrollTop = $(window).scrollTop();

http://docs.jquery.com/CSS/scrollTop
http://docs.jquery.com/CSS/height

通过How do I determine height and scrolling position of window in jQuery?

【讨论】:

    【解决方案2】:

    您需要考虑滚动位置。

    // Add the pageYOffset should fix the problem
    j(id).css('top',  (j(window).height()/2-j(id).height()/2) + window.pageYOffset);
    

    您还必须密切关注滚动事件并重新生成位置,以防它们上下滚动。

    【讨论】:

    • 太好了,因为您是 Stackoverflow 的新手,当有人给您正确的答案时,您会接受它。它给你声誉,也给他们声誉。
    猜你喜欢
    • 2018-06-04
    • 2019-04-30
    • 2020-04-04
    • 2015-05-12
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多