![](/img/trans.png)
[英]Run a function on first time page load not on page refresh in javascript
[英]Javascript function on the first load page
我正在尋找一個粘性頁腳,我發現了這個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);
}
我想在頁面加載事件中使用 JS 操作 DOM 元素不是一個好主意。 更好地使用 CSS 來做到這一點:
如果您在 CSS 中執行此操作,則應該不會遇到此問題,而且代碼行數很少,我做了一個快速模型作為示例。
HTML:
<header>Header</header>
<main>Main</main>
<footer>Footer</footer>
CSS:
header {
background-color:blanchedalmond;
height: 10vh;
min-height: 60px;
}
main {
background-color:beige;
height: 70vh;
min-height: 800px;
}
footer {
background-color:blanchedalmond;
height: 20vh;
min-height: 200px;
position: -webkit-sticky;
position: sticky;
bottom: 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.