使用Javascript将页脚保持在底部 [英] Keep the footer at the bottom with Javascript

查看:114
本文介绍了使用Javascript将页脚保持在底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正试图用Javascript将页脚保持在底部。结果如下:

At the moment I'm trying to keep the footer at the bottom with Javascript. This is the result:

document.getElementsByTagName('body').onload = function() {KeepFoot()};
var element = document.getElementById('container');
var height = element.offsetHeight;

function KeepFoot() {
    if (height < screen.height) {
        document.getElementById("footer").style.position = "fixed";
        document.getElementById("footer").style.bottom = "0";
        document.getElementById("footer").style.left = "0";
        document.getElementById("footer").style.right = "0";
    }
}

我的想法是获取div容器的高度并将其与电脑分辨率的高度进行比较。如果div容器的高度小于PC分辨率的高度,则设置为div footer position:fixed;

My idea was to take the height of the div container and compare it with the height of the resolution of the pc. If the height of the div container is smaller than the height of the resolution of the PC, set to the div footer position: fixed;

但是脚本中存在问题,因为它不起作用。

But there is a problem in the script because it doesn't work.

另一个问题,我创建的脚本可以保留底部的页脚?

Another question, the script that I created would be fine for keep the footer at the bottom?

HTML:

<html>
    <head>
        ...
    </head>
    <body>
        <div id="container">
            <div id="header"></div>
            <div id="content"></div>
            <div id="footer"></div>
        </div>
    </body>
</html>


推荐答案

DOMContentLoaded事件仅在文档准备就绪时触发,类似于jquery的 $(document.ready)

"DOMContentLoaded" event only fires when document is ready similar to jquery's $(document.ready).

并且,对于样式,您可以使用类而不是使用javascript设置每个样式。

and, for styles you can use class instead of setting each style using javascript.

代码

document.addEventListener("DOMContentLoaded", function (event) {
    var element = document.getElementById('container');
    var height = element.offsetHeight;
    if (height < screen.height) {
        document.getElementById("footer").classList.add('stikybottom');
    }
}, false);

#footer.stikybottom {
    position: fixed;
    bottom:0;
    left: 0;
    right:0;
}

<div id="container">
    <div id="header">header</div>
    <div id="content">Conent</div>
    <div id="footer">Something in footer</div>
</div>

这篇关于使用Javascript将页脚保持在底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆