2014-01-18 40 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 ..你的欢迎