如何在运行脚本之前确保身体有高度

问题描述 投票:0回答:2

如果页面短于视口,我想在astro框架内执行此脚本来调整页脚在页面末尾的位置(如果有更好的方法告诉我,但这不是这里的问题):

    window.onload = function () {
        const footer = document.querySelector('footer')
        if (!footer) return
        const bodyHeight = document.body.clientHeight
        const windowHeight = window.innerHeight
        if (bodyHeight < windowHeight) {
            footer.style.position = 'absolute'
            footer.style.bottom = '0'
            footer.style.width = '100%'
        }
    }

但是因为它是异步的,所以

document.body.clientHeight
等于 0 9 乘以 10 并且
window.onload
处理程序不会改变任何内容。我也尝试过
body.onload
但同样的事情。

这是我蹩脚的修补程序:

    window.onload = function () {
        const footer = document.querySelector('footer')
        if (!footer) return
        footer.style.display = 'none'
        setTimeout(function () {
            const bodyHeight = document.body.clientHeight
            const windowHeight = window.innerHeight
            if (bodyHeight < windowHeight) {
                footer.style.position = 'absolute'
                footer.style.bottom = '0'
                footer.style.width = '100%'
            }
            footer.style.display = 'block'
        }, 100) // Let the page load first
    }
javascript html css footer astrojs
2个回答
0
投票

您不需要使用 JavaScript 来实现此效果。 看看这个例子:

function AddContentToExemple(){
const contentElement = document.querySelector(".content");
contentElement.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum");
}
:root{
--footer-height : 80px;
}

.content {
  min-height: calc(100vh - var(--footer-height));
  padding: 40px 40px 0 40px;
  box-sizing: border-box;
}

.footer {
  height: var(--footer-height);
  background-color:red;
}


body {
  margin: 0;
}

footer {
  background: #42A5F5;
  color: white;
  padding: 0 20px;
}
<div class="content">
  <h1>Hello World</h1>
  <button onclick="AddContentToExemple()">Add Content</button>
</div>

<footer class="footer">
  Footer 
</footer>


0
投票

不确定它是否能解决您的问题,但我首先尝试使用此事件侦听器而不是 window.onload:

  document.addEventListener("DOMContentLoaded", (event) => {
      console.log("DOM fully loaded and parsed");
  });
© www.soinside.com 2019 - 2024. All rights reserved.