簡體   English   中英

使用Javascript將頁腳保持在底部

[英]Keep the footer at the bottom with 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>

我的功能非常好。 也許缺少的是函數調用。

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";
    }
}

KeepFoot();

看到這個jsfiddle

"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> 

該功能未在加載時調用。 您可以將函數KeepFoot直接附加到body標簽,而不是像這樣調用:

 document.getElementsByTagName('body').onload = function() {KeepFoot()};

或使用我下面的代碼:

 (function() {
    var offsetHeight = document.getElementById('container').offsetHeight;   
    var screenHeight = screen.height;

if(offsetHeight < screenHeight){
    document.getElementById("footer").style.position = "fixed";
    document.getElementById("footer").style.bottom = "0";
    document.getElementById("footer").style.left = "0";
}
})();

如果您想要的是將頁腳保持在頁面底部,則必須閱讀此內容。 cssreset.com/how-to-keep-footer-at-bottom-of-page-with-css/

你可以不用js來做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM