【发布时间】:2020-10-05 07:38:28
【问题描述】:
我正在寻找一个粘性页脚,我发现了这个 https://gist.github.com/robertvunabandi/b66dc9872f51c93af796094e08155731
这非常有用,但问题是当我刷新页面时,页脚首先出现在顶部,1 秒后它出现在底部的正确位置,有没有办法避免这种情况?我的意思是当我刷新页面时,页脚应该出现在底部?
window.addEventListener("load", activateStickyFooter);
function activateStickyFooter() {
adjustFooterCssTopToSticky();
window.addEventListener("resize", adjustFooterCssTopToSticky);
}
function adjustFooterCssTopToSticky() {
const footer = document.querySelector("#footer");
const bounding_box = footer.getBoundingClientRect();
const footer_height = bounding_box.height;
const window_height = window.innerHeight;
const above_footer_height = bounding_box.top - getCssTopAttribute(footer);
if (above_footer_height + footer_height <= window_height) {
const new_footer_top = window_height - (above_footer_height + footer_height);
footer.style.top = new_footer_top + "px";
} else if (above_footer_height + footer_height > window_height) {
footer.style.top = null;
}
}
function getCssTopAttribute(htmlElement) {
const top_string = htmlElement.style.top;
if (top_string === null || top_string.length === 0) {
return 0;
}
const extracted_top_pixels = top_string.substring(0, top_string.length - 2);
return parseFloat(extracted_top_pixels);
}
【问题讨论】:
-
使用CSS设置位置到底部?无论如何,这很可能都可以通过 CSS 完成,但如果你想这样做,那也没关系。
标签: javascript html footer