最近在开发博客过程中,遇到有些body的height是比window的height要低的,然后就出现了footer在页面中间的尴尬样子。那么这种情况怎么解决呢:
首先,写一个footer标签:
<footer class="fixed-bottom"> ???????<p>自定义内容</p></footer>
然后,对footer和footer的class:fixed-bottom分别进行css样式定制:
1 footer { 2 ????text-align: center; 3 ????background-color: #d2d8dd; 4 ????padding: 1.5em; 5 ????font-size: 16px; 6 } 7 ?8 footer.fixed-bottom { 9 ????position: fixed;10 ????bottom: 0;11 ????width: 100%;12 }
为什么要分别写两个css样式呢?因为footer这个的样式,只不过是调整footer内的内容格式而已,它本身即可随页面的高度而紧随其后,然而当页面内容较少时就会在页面中间出现。为了解决这个问题就需要添加footer的class对应的css样式,样式属性中positon:fixed以及bottom:0使得footer会一直固定显示在页面底部,类似于bootstrap的固定导航栏那样挡在底部,不能随页面内容的翻滚而改变。这种方式确实实现了页面内容不足时可以使footer固定在底部的需求,但是对于页面内容很多时,却又在页面底部一直显示影响浏览心情。
那么怎么让什么合适的时候用footer的css样式,什么合适的时候用二者都具备的css样式呢?这时候就需要用一个js脚本来判断body的高度和window的高度,使得class类属性自动添加或消除:
1 <script type="text/javascript"> 2 ??????$(function(){ 3 ??????????function footerPosition(){ 4 ??????????????$("footer").removeClass("fixed-bottom"); 5 ??????????????var contentHeight = document.body.scrollHeight,//网页正文全文高度 6 ??????????????????winHeight = window.innerHeight;//可视窗口高度,不包括浏览器顶部工具栏 7 ??????????????if(!(contentHeight > winHeight)){ 8 ??????????????????//当网页正文高度小于可视窗口高度时,为footer添加类fixed-bottom 9 ??????????????????$("footer").addClass("fixed-bottom");10 ??????????????} else {11 ??????????????????$("footer").removeClass("fixed-bottom");12 ??????????????}13 ??????????}14 ??????????footerPosition();15 ??????????$(window).resize(footerPosition);16 ?????});17 </script>
最后,如此一来,就实现了在两种情况下的footer永远在底部显示,并且可以随页面滚动。
html中footer如何一直保持在页底
原文地址:https://www.cnblogs.com/cpl9412290130/p/10017960.html