开发者

Stick element to top after scroll

I want to make container/div in sidebar moving/following along with page scrolling down. It is not just a position:fixed container. It will move only when it shoul开发者_如何学Cd disappear being scrolled down. What is the best practice to implement?

Thank you


Say we want to:

  1. start at 260px from top (as defined in CSS)
  2. stick at 24px from top (as defined in JS)

var $sticky = $("#sticky"),
    pos = {
      abs : {position: "absolute",  top: parseInt($sticky.css("top"), 10) },
      fix : {position: "fixed",     top: 24 /* <<< SET AS DESIRED */ },
    };

$(window).on("load scroll", function() {
  var canFix = $(this).scrollTop() >= pos.abs.top - pos.fix.top;
  $sticky.css( pos[ canFix? "fix" : "abs" ] );
});
body{
  height: 2000px;
  border: 4px dashed #444;
}
#sticky{
  height: 100px;
  background: #0bf;
  position:absolute;
  top: 260px;   /* <<< SET AS DESIRED */
}
SCROLL!
<div id="sticky">STICK ME AT 24 FROM TOP</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜