【问题标题】:Jquery offset function making the top style a negative number in FirefoxJquery偏移函数使顶部样式在Firefox中为负数
【发布时间】:2012-04-16 12:33:15
【问题描述】:

我打算创建一个具有固定定位的自定义警报框。它在 chrome 中运行良好,但我无法在 Firefox 中获得正确的动态位置。

我将模态容器设置为等于文档的大小

$('#modalContainer').height($.getDocHeight());

然后#alertBox div 位于 modalContainer 中并具有 position:fixed 样式。

我正在使用 jquery 偏移函数来设置 #alertBox 的顶部和左侧值,如下所示:

var off_top=$(window).height()/3-$('#alertBox').height()/3;
var off_top=100;
var off_left=$(window).width()/2- $('#alertBox').width()/2;
$('#alertBox').offset({top:off_top,left:off_left});

在 chrome 中,顶部值设置为 100px 并显示在屏幕上。在 Firefox 中,我得到了一个令人讨厌的大数字,比如 -1084px。

当我将 .offset() 值和 position() 值都输出到 console.log 时,它们在 chrome 中是相同的。然而,在 Firefox 中,虽然偏移值输出的正是我设置的值,但 .position() 函数输出了令人讨厌的大数字。

这是已知的浏览器不一致吗?我需要以不同的方式解决这个问题吗?

【问题讨论】:

标签: jquery css firefox dom css-position


【解决方案1】:

尝试将您的初始位置设置为

$('#modalContainer').height(document.documentElement.clientHeight);

你应该得到height of the viewport

作为每次计算偏移量的替代方法,您可以在警报框中使用margin: autoposition: absolute。您可能仍想设置模态容器的高度,但所有警报的居中都会自动完成。

HTML

<body>
<p>Lorum ipsum ... </p>
<div id='modalContainer'>
    <div id='alertBox'>
        <h1>Beware!</h1>
    </div>
</div>
</body>

CSS

#modalContainer {
    position: absolute;
    width: 100%;
    margin: 0;
    padding: 0;
}
#alertBox {
    width: 300px; /*sample*/
    height: 200px; /*sample*/
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

JavaScript

$('#modalContainer').height(document.documentElement.clientHeight);

【讨论】:

  • 谢谢,我结合了这个答案以及我所拥有的一些答案。当浏览器滚动时,绝对定位不起作用,所以我保持位置:固定,并添加一个边距值。当我这样做时,我不需要动态更改最高值。为了让盒子水平居中,我仍然使用左偏移,因为自动边距样式没有采用。我认为这是因为我在动态添加和删除#alertBox。
  • @Ed Sullivan 很高兴知道。让我好奇将#modalContainer 的位置设置为固定是否可行。可能必须尝试一下。
  • 我不确定这在这种情况下是否有效。 modalContainer 需要覆盖整个 body,这样其他 z-indexes 较低的属性就不能点击了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多