问题
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";
}
}
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>
回答1:
"DOMContentLoaded"
event only fires when document is ready similar to jquery's $(document.ready)
.
and, for styles you can use class instead of setting each style using javascript.
Code
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>
回答2:
I thing your function works very well. maybe what is missing is the function calling.
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();
see this jsfiddle
回答3:
The function is not being called on load. You can attach the function KeepFoot directly to the body tag like this Instead of calling like this:
document.getElementsByTagName('body').onload = function() {KeepFoot()};
or use my code from below:
(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";
}
})();
回答4:
If what you want is to maintain the footer on the bottom of the page, you must read this. cssreset.com/how-to-keep-footer-at-bottom-of-page-with-css/
You can do it without js.
来源:https://stackoverflow.com/questions/30276950/keep-the-footer-at-the-bottom-with-javascript