jQuery实现页脚永远固定在页面底部
[ 2016/05/01, JavaScript , 4882阅, 0评 ]

QQ截图20160501230328.jpgstickyfooter.png

使用下面的jQuery代码,可以轻松的帮我们实现页脚永远固定在页面底部(页脚永远固定在页面的底部,而非永远固定在浏览器窗口的底部,换句话说,就说当页面主内容没有显示屏幕高时,页脚固定在显示器屏幕的底部,但当页面内容超过显示器屏幕高度时,页脚又会跟随内容往下沉,但页脚都永远固定在页的底部),使用这种方法有几个地方需要注意:

1. 确保正常引入了jQuery版本库,并正常调入了上面那段jQuery代码;

2. 确保<div id=”footer”>是在body中最后;

3. 确保在html,body中没有设置高度为100%。

优点:

结构简单,无需外加无用标签,兼容所有浏览器,不用另外写特别样式。页脚可以不固定高度。

缺点:

在不支持js的浏览器中无法正常显示,另外每次改变浏览器大小会闪动一下。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery实现页脚永远固定在页面底部</title>
<style>
*{margin:0;padding:0}
.clearfix:after,.clearfix:before{content:"";display:table}
.clearfix:after{clear:both}
.clearfix {zoom:1; /* IE <8 */}   
#footer{height: 60px;background: #fc6;width: 100%;}
/*==========其他div==========*/
#header{padding:10px;background:#0f0}
#left{width:18%;float:left;margin-right:2%;background:orange}
#content{width:60%;float:left;margin-right:2%;background:green}
#right{width:18%;float:left;background:#ff0}
</style>
</head>

<body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() {
var footerHeight = 0,
footerTop = 0,
$footer = $("#footer");
positionFooter();
//定义position Footer function
function positionFooter() {
//取到div#footer高度
footerHeight = $footer.height();
//div#footer离屏幕顶部的距离
footerTop = ( $(window).scrollTop()+$(window).height()-footerHeight)+"px";
/* DEBUGGING STUFF
console.log("Document height: ", $(document.body).height());
console.log("Window height: ", $(window).height());
console.log("Window scroll: ", $(window).scrollTop());
console.log("Footer height: ", footerHeight);
console.log("Footer top: ", footerTop); console.log("-----------")
*/
//如果页面内容高度小于屏幕高度,div#footer将绝对定位到屏幕底部,否则div#footer保留它的正常静态定位
if ( ($(document.body).height()+footerHeight) < $(window).height()) {
$footer.css({
position: "absolute"
}).stop().animate({
top: footerTop
});
} else {
$footer.css({
position: "static"
});
}
}
$(window).scroll(positionFooter).resize(positionFooter);
});
</script>
<div id="header">Header Section</div>
<div id="page" class="clearfix">
<div id="left">Left sidebar</div>
<div id="content">Main Content</div>
<div id="right">Right Content</div>
</div>
<div id="footer">Footer Section</div>
</body>
</html>

有朋自远方来...评论一下呗O(∩_∩)O