Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - How to make conditionally "sticky" footer?

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...