【问题标题】:Stick a footer to bottom - without jQuery将页脚粘贴到底部 - 没有 jQuery
【发布时间】:2015-05-19 15:45:44
【问题描述】:

在尝试解决这个问题时,我只遇到了 jQuery 插件。但由于我的网站很小,我只使用 jQuery 替代品cash

我想实现以下行为:

  • 当页面内容不能完全填满视口时,坚持到底。​​li>
  • 如果内容填满整个屏幕,则在内容下方结束。

根据我从 jQuery 插件中读取的内容,我需要计算内容的高度,从当前视口中减去该高度,然后查看结果是否为负。

但由于我不使用 jQuery,我是怎么做到的?

我的 HTML 结构是(类似于)这个:

<!DOCTYPE html>
<html>
<head>
    <title>...</title>
</head>
<body>
    <div id="MainPage">
        <div class="menu"></div>
        <div class="content"></div>
    </div>
    <footer></footer>
</body>
</html>

除了页脚之外的所有内容都在包装中div

【问题讨论】:

标签: javascript html


【解决方案1】:

Ryan Fait 的 HTML5 Sticky Footer 就是一个很好的例子(当您知道页脚的高度时)。

http://ryanfait.com/html5-sticky-footer/

Ryan Fait 的 HTML5 粘滞页脚

HTML

<body>

    <div class="wrapper">

        <div class="push"></div>

    </div>

    <footer></footer>
</body>

CSS

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
footer, .push {
    height: 155px; /* '.push' must be the same height as 'footer' */
}

如果你不知道高度,你可以使用:

HTML

<body>
    <footer></footer>
</body>

CSS

html {
    position: relative;
    min-height: 100%;
}

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
}

jQuery

​​>
$( 'body' ).css( 'margin-bottom', $( 'footer' ).height() );

只是普通的 Javascript

document.getElementsByTagName('body')[0].style.marginBottom = document.getElementsByTagName('footer')[0].offsetHeight + 'px';

【讨论】:

  • 我玩弄了您的代码示例,并想出了一个现在适合我的示例。非常感谢!
【解决方案2】:

您可以使用以下方法获取浏览器窗口的高度(没有滚动条/工具栏):

window.innerHeight

然后您可以使用以下方法获取 MainPage div 的高度:

document.getElementById("MainPage").offsetHeight

请注意,window.innerHeight 将包含水平滚动条的高度(如果页面上存在水平滚动条),因此如果需要,请考虑它。

一旦你有了这两个属性,你就可以计算出你需要的尺寸。

如果您只想将页脚粘贴到页面底部,您也可以使用 CSS,例如

footer{
    position: fixed;
    bottom: 0px;
}

【讨论】:

    【解决方案3】:

    window.innerHeight 给出屏幕的高度,getElementById().height 给出元素的高度。
    因此,在您的情况下,您将使用纯 JS:

    if (document.getElementById('MainPage').offsetHeight < window.innerHeight) {
        document.getElementsByTagName('footer')[0].style.position='fixed';
    }
    

    或者您可以添加一个“fixedFooter”类,而不是使用document.getElementsByTagName('footer')[0].classname += ' fixedFooter'; 设置CSS 属性,并通过CSS 设置该类的样式。这会给你更多的控制权。例如:

    .fixedFooter {
        bottom: 0;
        position: fixed;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-15
      • 2014-11-09
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2011-01-22
      相关资源
      最近更新 更多