2011-08-10 39 views
0

我有一個div容器,它的頂邊應該被設置爲$(window).height()的依賴關係,所以首先我嘗試了一些東西像這樣:

 $("div#outerstart").css("margin-top",$(window).height() -805+"px"); 

它工作得很好,但上邊距不應該是負的,所以我想這:

 $("div#outerstart").css("margin-top",function() { 
     if ($(window).height() < 805) { 
      0+"px" 
     } else { 
      $(window).height() -805+"px" 
     } 
    }); 

或也

if ($(window).height() < $(document).height()) {... 

但它顯示沒有效果並且未設置邊距頂部。你有什麼建議嗎?

+0

使用關鍵字return?其功能,而不是直接聲明 –

+0

@Marek Sebera:寫一個答案,而不是評論? – thirtydot

回答

3

,讓我們改變你的代碼使用來自函數

$("div#outerstart").css("margin-top",function() { 
    if ($(window).height() < 805) { 
     return "0px"; 
    } else { 
     return ($(window).height() -805)+"px"; 
    } 
}); 
+0

謝謝!它的工作 – sinini

+0

很高興爲您提供幫助,如果我的回答是正確的,請在答案左側使用綠色代碼。這是如何工作在這裏 –

+1

是的,我試圖,但我不得不等待5分鐘接受;) – sinini

3

return關鍵字一個簡單的辦法是使用Math.max,而不是匿名函數:

$("div#outerstart").css("margin-top", Math.max(0, $(window).height()-805)+"px");