将页脚粘到底部 - 没有jQuery

时间:2015-05-17 17:52:43

标签: javascript html

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

我想实现以下行为:

  • 当页面内容无法完全填满视口时,请坚持到底。
  • 如果内容填满屏幕,则最终会在内容下方。

根据我从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

3 个答案:

答案 0 :(得分:2)

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

window.innerHeight

然后你可以使用:

获得MainPage div的高度
document.getElementById("MainPage").offsetHeight

请注意,如果页面上有一个水平滚动条,window.innerHeight将包含水平滚动条的高度,因此如果需要,请对其进行说明。

拥有这两个属性后,您可以计算出所需的大小。

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

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

答案 1 :(得分:2)

一个很好的例子(当知道你的页脚高度时)是Ryan Fait的HTML5粘性页脚。

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

Ryan Fait的HTML5 Sticky Footer

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 :(得分:1)

:(为您提供屏幕高度,window.innerHeight为您提供元素的高度。
所以在你的情况下,你有简单的JS:

getElementById().height

或者你可以添加一个类&#39; fixedFooter&#39;而不是使用if (document.getElementById('MainPage').offsetHeight < window.innerHeight) { document.getElementsByTagName('footer')[0].style.position='fixed'; } 设置CSS属性,并通过CSS设置此类的样式。这会给你更多的控制权。 E.g:

document.getElementsByTagName('footer')[0].classname += ' fixedFooter';