jquery - jQuery.css 的不同值 ('top-margin' ) 边距 :auto based on browser

标签 jquery html css

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

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.

请指教。

最佳答案

结果在 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);

关于jquery - jQuery.css 的不同值 ('top-margin' ) 边距 :auto based on browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150348/

相关文章:

javascript - 更改按钮的文本以及 jquery 中的 fadetoggle 函数

jquery - 在固定元素上滚动时在主体上滚动,反之亦然

php - 每个循环多个ajax php请求

jquery - 如何垂直交错这些 HTML 元素?

javascript - 日期选择器和图像 slider 冲突

php - 使用 dompdf 打印 pdf 表格无法正常工作

html - 将 SVG/图像代码放入 &lt;/style&gt;

javascript - HighCharts + reveal.js 图表大小

python - 使用狮身人面像数学时波兰语字母

html - 从数据库呈现文本时,Django 不显示换行符