微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Javascript将页脚保持在底部

目前我正试图用 Javascript将页脚保持在底部.这是结果:
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;

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

一个问题,我创建的脚本可以将页脚保持在底部吗?

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).

并且,对于样式,您可以使用类而不是使用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>

原文地址:https://www.jb51.cc/js/157473.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐