2014-01-18 85 views
6

我有一個網頁有幾頁。每頁都有不同的高度(很明顯,但我提到它)。只有當頁面爲「short」時,纔將頁腳放在底部

我想實現的是,如果頁面的內容低於瀏覽器視口,頁腳標籤將獲得固定的位置並且將與頁面底部對齊。

iv'e試過這個js:

$(function(){ 
if ($(document).height() > $("footer").offset().top+44) { 
     $("footer").addClass('fixbottom'); 
    } 
} 
}); 

$(window).resize(function() { 
    if ($(document).height() > $("footer").offset().top+44) { 
     $("footer").addClass('fixbottom'); 
    } 
}); 

和CSS:

.fixbottom { 
    width: 100%; 
    position: fixed; 
    bottom: 0; 
} 


footer { 
height:44px; 
    background: #7abde9; 
    color: #ffffff; 
    text-align: center; 
} 

在我的jQuery頂部+ 44,因爲我的頁腳標籤44的高度 iv'e使用準備文件並調整窗口大小以確保所有情況都應該符合,但不幸的是,這在任何情況下都不起作用。

任何幫助應該很大appriciated

+0

參見[這](http://ryanfait.com/resources/footer- ) – Peter

回答

8

你不需要爲這個JavaScript。

有一種叫做「stickyfooter」的方法,它提供了一種方法讓頁腳始終處於底部,即使內容不多。

下面是一個簡單的例子:

html, body { 
    height:100%; 
} 

#wrapper { 
    position: relative; 
    min-height:100%; 
} 

#main { 
    padding-bottom: 44px; 
} 

footer { 
    height: 44px; 
    position: absolute; 
    bottom: 0; 
    left: 0; 
    width: 100%; 
} 

看到這個fiddle,看看它是如何工作的。

+1

Micha,我只想在頁面內容短於視口時附加到底部 – sd1sd1

+1

更改了CSS並將一些JavaScript添加到了我的[fiddle](http://jsfiddle.net/vYXR7/3 /)。它似乎沒有在那裏工作,但在實際的Chrome和Firefox中的測試頁上嘗試。它在那裏工作。 – MichaB

+0

如何使頁腳高度不固定,如何使這項工作?我有幾頁頁腳的內容(喜歡和圖標)根據登錄的用戶角色而改變 – Rohan

1

在普通的JavaScript:

if (window.innerHeight > document.body.offsetHeight) { 
     // code to make the footer stick to bottom 
} 
3

你只能用CSS解決你的問題。

您需要爲您的內容添加一個元素,併爲下面的頁腳添加一個元素。

<div id="container"> 
    <div id="content"> 
    <div id="main"> 
     Content 
    </div> 
    </div> 
    <div id="footer"> 
    Footer 
    </div> 
</div> 

給#content一個100%的最小高度,併爲#footer設置一個高度和反向頁邊距(與高度相同)。爲了保護#content中最後一個元素的重疊,請設置margin-bottom。

#content { 
    min-height: 100%; 
} 
#footer { 
    height: 3em; 
    margin-top: -3em; 
} 
#main { 
    padding-bottom: 3em; /** height of #footer */ 
} 

下面是一個例子:

http://jsfiddle.net/GB4vA/1/

卡梅倫亞當斯寫了一篇關於您的問題的文章。 http://www.themaninblue.com/writing/perspective/2005/08/29/

2

JS Fiddle

var shortContent = function() {  
    if($(window).height() > $('body').height()) { 
     $('footer').addClass('shortContent'); 
    } 

}; 

(function(){ 

    shortContent(); 

    $(window).resize(function() { 
    shortContent(); 
    }); 

}()); 

simplyfied的JS,並使它沒有太多的CSS

@MichaB工作你需要的jQuery M8

1
<script> 
function hideMe(id) 
{ 
    var box=document.getElementById(id); 
    box.style.display="none"; 

} 
var bodyHeight=document.getElementById("body").offsetHeight, 
    windowHeight=window.innerHeight; 

if(bodyHeight<windowHeight) 
{ 


    var footer= document.getElementById("footer"); 
    footer.style.position="absolute"; 
    footer.style.left="0px" 
    footer.style.top=windowHeight-footer.offsetHeight+'px'; 
    footer.style.width='100%'; 

} 
<script> 

上的HTML代碼只是把ID = 「頁腳」 到您的頁腳DIV ..你的歡迎