如何有条件地使“粘性"变为“粘性".页脚? [英] How to make conditionally "sticky" footer?

查看:75
本文介绍了如何有条件地使“粘性"变为“粘性".页脚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使页脚发粘",但高度不同,因此不能使用我发现的大多数方法或flexbox.有没有办法用javascript检查div下有多少空间,所以我可以增加那么多的余量?

I am trying to make my footer "sticky" but the heights vary so can't use most of the methods I've found or flexbox. Is there any way to check with javascript how much space is under a div so I can add that much margin?

html看起来像这样:

The html looks like this:

  <container>
     <header></header>
     <body><sometimes sub content></sub content></body>
     <footer></footer>
   </container> 

还尝试将页脚放在容器外,看到在某些解决方案中,但它们都需要固定高度.

Also tried putting the footer outside of the container, saw that in some solutions, but again they all require a fixed height.

推荐答案

您可以检查是否为$(document).height() > $(window).height().这将告诉您内容的高度是否大于视口.如果是这样,请将页脚保留在原处.如果文档高度为< =视口高度,请添加使页脚为粘性.像这样:

You can check if $(document).height() > $(window).height(). That will tell you if the height of the content is longer than the viewport. If so, leave the footer where it is. If the doc height is <= the viewport height, add make the footer sticky. Like so:

要查看粘性和非粘性之间的差异,请运行下面的代码片段,以使页脚位于页面底部.要在页脚有粘性的地方查看它,请以全屏模式运行该代码段(在代码段输出的右上角).您也可以只在全屏模式下运行它,然后缩小浏览器大小-它会根据窗口调整大小重新计算.

To see the difference between sticky and non-sticky, run the snippet below to have the footer at the bottom of the page. To view it where the footer is sticky, run the snippet in full screen mode (on the top right corner of the snippet output). You can also just run it in full screen mode and then shrink your browser size down - it recalculates on window resize.

$(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>

这篇关于如何有条件地使“粘性"变为“粘性".页脚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆