当footer类块加上内容content类块不足于撑开页面的时候让footer类块固定在底部,反之默认展示

      发布在:前端技术      评论:0 条评论

这里使用jquery实现,所以确保你已经引入了 jQuery 库。然后,可以使用以下代码来实现:

<!DOCTYPE html><html><head>    <title>固定底部 Footer</title>    <style>        body {            margin: 0;            padding: 0;            height: 100%;        }                .content {            min-height: 100%;            padding-bottom: 60px; /* 这里的值应该是你的 footer 高度加上一些额外的空间 */        }                .footer {            position: fixed;            left: 0;            bottom: 0;            width: 100%;            height: 60px; /* 这里的值应该是你的 footer 高度 */            background-color: #f5f5f5;        }    </style>    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body>    <div class="content">        <!-- 页面内容 -->    </div>    <!-- footer 类块 -->    <div class="footer">        <!-- footer 内容 -->    </div>    <script>          function resize(h){      var contentHeight = jQuery(".content").height();      //获取.content到顶部的偏移高度      var contentTop = jQuery(".content").offset().top;      var footerHeight = jQuery(".footer").height();      var windowHeight = jQuery(window).height();      if (contentHeight+contentTop+footerHeight+h < windowHeight) {        jQuery(".footer").css("position", "fixed");      } else {        jQuery(".footer").css("position", "static");      }    }    jQuery(window).on("load", function() {      resize(0);    });        jQuery(window).resize(function() {          resize(0);        });    </script></body></html>

在这个示例中,我们使用了 CSS 来定义内容和 footer 类块的样式。.content 类设置了最小高度为 100% 并添加了底部边距,以确保内容区域至少撑满整个页面高度,并为 footer 留出空间。.footer 类设置了固定定位,将其固定在页面底部。

通过使用 jQuery,在页面加载完成时和窗口大小调整时,我们会计算内容区域高度和窗口高度,并根据条件来更改 footer 类块的定位。如果内容区域高度小于窗口高度,则将 footer 设置为固定定位;否则将 footer 设置为默认定位(即 static)。

这样就能实现当内容不足以撑开页面时,footer 类块固定在底部;而当内容超过页面高度时,footer 类块会随着页面滚动。


相关文章
热门推荐