【问题标题】:Different values for jQuery.css('top-margin') with margin:auto based on browserjQuery.css('top-margin') 的不同值与 margin:auto 基于浏览器
【发布时间】:2014-01-21 03:22:46
【问题描述】:

让我试着说明一下,我的问题是为什么不是所有的浏览器都以同样的方式对待它。

html

<body>
    <div id="container"></div>
    <div id="footer"></div>
</body>

CSS

body{
    height:100%;
    width:100%;
    position:relative;
}
.container{
    height:800px;
    width:800px;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin: auto;
}
.footer{
    position:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

jQuery

var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
$('#footer').css('top',footertop);

我有一个绝对水平和垂直居中的容器 div。然后我试图将页脚的“顶部”设置为容器的高度加上容器的上边距。 (这样它就在容器的正下方)。此方法适用于某些浏览器(Chrome、Opera、Safari、IE9+),但不适用于其他浏览器(Firefox、IE8-)。

我假设 IE8 及更早版本不支持这种方法,这很好,但在 Firefox 中,footertop 的值始终等于 $('#container').css('height')

如果我执行 console.log(parseFloat($('#container').css('margin-top'))) 我会根据浏览器的高度得到一个正整数,但在 Firefox 上总是0.

请指教。

【问题讨论】:

标签: jquery html css


【解决方案1】:

结果在 Firefox 中,margin-top、margin-bottom、margin-left 和 margin-right 的计算值都以 0 结尾,并且 top、bottom、left 和 right 属性具有您期望找到的值在边缘。

这是我现在可以在所有浏览器上使用的 jquery:

if(parseFloat($('#container').css('margin-top')) == 0){
    var footertop = (parseFloat($('#container').css('top'))+parseFloat($('#container').css('height')))+'px'; //firefox fix
}else{
    var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
}
$('#footer').css('top',footertop);

【讨论】:

    猜你喜欢
    • 2022-10-07
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-09-02
    • 2012-03-25
    • 1970-01-01
    相关资源
    最近更新 更多