2013-06-03 24 views
1
<script> 
    $(document).ready(function() { 
     var footerheight = $('#footer').height(); 
     $('#footer').css('height', footerheight); 
     $('#footer').css('marginTop', footerheight); 
     $('#nonfooterinner').css('paddingBottom', footerheight); 
    }); 
    $(window).bind("resize", function() { 
     var footerheight = $('#footer').height(); 
     $('#footer').css('height', footerheight); 
     $('#footer').css('marginTop', footerheight); 
     $('#nonfooterinner').css('paddingBottom', footerheight); 
    }); 
</script> 

<body> 
    <div id="nonfooterouter"> 
     <div id="nonfooterinner"> 
      body 
     </div> 
    </div> 
    <div id="footer"> 
     xxx 
    </div> 
</body> 

該腳本獲取#footer div的高度,並將其設置爲內部包裝體(#nonfooterinner)的底部填充和#footer的頂部邊距。但是,#footer的上邊距必須是該數字的負值。如何將腳本中的變量「footerheight」轉換爲僅用於marginTop值的負數?JQuery變量:如何將正高度轉換爲負邊距?

回答

1

Example on jsFiddle

只要將它設置爲負

$('#footer').css('marginTop', - footerheight); 
+0

我不知道你能做到這一點,真棒。問題是現在爲什麼總是隻有在IE和其他地方沒有? – user2441996

+0

@ user2441996 IE有一個「px」的錯誤。如果你想避免這個問題,可以使用'parseInt()'。 – Edward

0

您可以使用parseInt()將字符串轉換爲int。請在下面檢查代碼:

var footerheight = $("#footer").height(); 
var marginTop = parseInt(footerheight) * -1; 
$("#footer").css("marginTop", marginTop + "px"); 
2
var footerheight = $('#footer').height(); 

    $('#footer').css('margin-left', footerheight *-1); 
+0

請向您的解決方案添加一些解釋,說明它如何解決問題以及提問者做錯了什麼或缺少什麼。 –

+0

這是一個很好的答案Avinash Saini。它是如何工作的? –

0
var footerheight = $('#footer').height(); 
footerheight =-Math.abs(footerheight);