当前位置: 首页 > web>阅读正文

bootstrap实现粘性页脚

2022.2.13 朱丰华 1647 次 留下评论 2173字

当页面内容不足时,页脚也始终在底部

方法一:使用absolute定位

这是一个官方给的示例,这里稍微做了一些改动:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bootstrap 101</title>
    <link rel="stylesheet" href="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
    <script src="https://www.52dixiaowo.com/tools/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script src="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>
</head>
<body>
    <h1>Hello,Bootstrap3!</h1>
    <footer class="footer">
        <div class="container">
          <p class="text-muted">Place sticky footer content here.</p>
        </div>
      </footer>
<style>
    /* Sticky footer styles
    -------------------------------------------------- */
    html {
    position: relative;
    min-height: 100%;
    }
    body {
    margin-bottom: 60px; /* Margin bottom by footer height */
    }
    .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px; /* Set the fixed height of the footer here */
    background-color: #f5f5f5;
    }

</style>
</body>
</html>

上面这个方法,存在一些问题,首先是页脚大小必须固定,第二个是在使用js动态加载数据时页脚失灵,于是这里有了第二个方法

方法二:使用js动态加载

当页面加载完毕时,判断当前页面的大小,如果页面大小等于窗口大小,则说明没有更多内容,此时把页脚固定在底部(navbar-fixed-bottom类),而如果页面内容超过本窗口,那么取消固定页脚即可。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bootstrap 101</title>
    <link rel="stylesheet" href="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
    <script src="https://www.52dixiaowo.com/tools/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script src="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>
</head>
<body>
    <h1>Hello,Bootstrap3!</h1>

<footer class="navbar navbar-default navbar-inverse copyright">
    <p class="text-center" style="color:#9d9d9d;margin-top:15px;">Copyright © 52的小窝 2022</p>
</footer>

<style>
    .copyright{
        margin-bottom: 0px;
    }
</style>
<script>
    $(function () {
      if($(window).height()==$(document).height()){
        $(".copyright").addClass("navbar-fixed-bottom");
      }
      else{
        $(".copyright").removeClass(" navbar-fixed-bottom");
      }
    });
</script>
</body>
</html>

因动态加载html问题,若无法显示效果请复制代码在本地调试。

本篇完,还有疑问?留下评论吧

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注