我试图让我的页脚“有粘性”,但高度各不相同,所以不能使用我发现的大多数方法或 flexbox。有什么方法可以用 javascript 检查 div 下有多少空间,以便我可以添加那么多的边距?
html 看起来像这样:
<container>
<header></header>
<body><sometimes sub content></sub content></body>
<footer></footer>
</container>
还尝试将页脚放在容器外部,在某些解决方案中看到了这一点,但同样它们都需要固定高度。
最佳答案
您可以检查是否 $(document).height() > $(window).height()
。这将告诉您内容的高度是否比视口(viewport)长。如果是这样,请将页脚留在原处。如果文档高度 <= 视口(viewport)高度,请添加使页脚变粘。像这样:
要查看粘性和非粘性之间的区别,请运行下面的代码段以使页脚位于页面底部。要在页脚粘滞的位置查看它,请在全屏模式下运行代码段(在代码段输出的右上角)。您也可以在全屏模式下运行它,然后缩小您的浏览器大小——它会在窗口调整大小时重新计算。
$(window).on("load resize", function() {
// if content height <= viewport height, make footer sticky
// else leave footer at the bottom of the content.
$(".footer").toggleClass("sticky", $(document).height() <= $(window).height());
});
.footer {
width: 100%;
background-color: #555588;
color: white;
}
.sticky {
position: fixed;
bottom: 0;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre style="font-size: 16px;">
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
content
</pre>
<div class="footer">foo foo foo <br/>foo<br/>foo<br/></div>
关于javascript - 如何有条件地制作 "sticky"页脚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466921/