简体   繁体   English

jQuery.css('top-margin')具有margin:auto的不同值(基于浏览器)

[英]Different values for jQuery.css('top-margin') with margin:auto based on browser

Let me try to lay this out, my question is why don't all the browsers treat this the same way. 让我尝试说明一下,我的问题是为什么不是所有的浏览器都以相同的方式对待这一点。

html HTML

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

Css 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 jQuery的

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

I have a container div that is absolutely centered horizontally and vertically. 我有一个容器div,它在水平和垂直方向绝对居中。 Then I am attempting to set the 'top' of the footer to be the height of container plus the top margin of container. 然后,我尝试将页脚的“顶部”设置为容器的高度加上容器的顶部边缘。 (So that it ends up right underneath the container). (这样它就可以在容器正下方结束)。 This method works on some browsers (Chrome,Opera,Safari,IE9+) but doesn't work on others (Firefox,IE8-). 此方法适用于某些浏览器(Chrome,Opera,Safari,IE9 +),但不适用于其他浏览器(Firefox,IE8-)。

I am assuming IE8 and earlier doesn't support this method, and that's fine, but in Firefox the value of footertop is always equal to $('#container').css('height') 我假设IE8和更早的版本不支持此方法,这很好,但是在Firefox中,页脚的值始终等于$('#container')。css('height')

If I do a console.log(parseFloat($('#container').css('margin-top'))) I get a positive integer depending on the height of my browser, but on Firefox it is always 0. 如果我执行console.log(parseFloat($('#container')。css('margin-top'))),则我将得到一个正整数,具体取决于浏览器的高度,但是在Firefox上,它始终为0。

Please advise. 请指教。

Turns out in firefox the computed value for margin-top, margin-bottom, margin-left and margin-right all end up as 0 and the top,bottom,left and right attributes have the values that you would expect to find in the margins. 在firefox中,margin-top,margin-bottom,margin-left和margin-right的计算值最终都为0,并且top,bottom,left和right属性具有您期望在margins中找到的值。

here is my jquery that works on all browsers now: 这是我的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM