JS实现让页脚一直固定在页面底部

本文介绍了一种使用JavaScript实现页脚始终显示在浏览器可视范围底部的方法。通过监听滚动和调整页脚的位置,确保其始终处于屏幕底部,提高了用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JS实现页脚在浏览器可视范围内始终置底。

如下图所示:

154816_Vfp8_2343527.png

代码如下: 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>JS实现让页脚一直固定在页面底部</title>
		<meta name="generator" content="editplus" />
		<meta name="author" content="" />
		<meta name="keywords" content="" />
		<meta name="description" content="" />

		<style type="text/css">
			*{margin:0px;padding:0px;}
			body{font-size:12px;font-family:"微软雅黑";color:#ddd;background:#eee;}

			.header{width:100%;height:98px;background:#111;padding:1px 0px;color:#fff;font-size:24px;text-align:center;}
			
			.content{width:1500px;height:700px;background:#004f27;margin:0px auto;color:#fff;font-size:24px;text-align:center;}
	
			.footer{width:100%;height:50px;background:#111;color:#fff;font-size:24px;text-align:center;}
		</style>
	</head>
	<body>
		<div class="header">头部</div>

		<div class="content">内容区域</div>

		<div class="footer">底部</div>

	</body>

	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		$(window).bind("load", function() {
			var footerHeight = 0;
			var footerTop = 0;
			 
			positionFooter();
			 
			function positionFooter() {
				// 获取页脚的高度
				footerHeight = $(".footer").height();
				// 获取页脚的高度
				/*
					scrollTop() 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 
				*/
				footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
				//如果页面内容高度小于屏幕高度,div#footer将绝对定位到屏幕底部,否则div#footer保留它的正常静态定位
				if(($(document.body).height()+footerHeight) < $(window).height()) {
					$(".footer").css({ position: "absolute",left:"0" }).stop().css({top:footerTop});
				}
			}
			$(window).scroll(positionFooter).resize(positionFooter);
		});
	</script>

</html>

 

转载于:https://my.oschina.net/AaronDMC/blog/790408

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值