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:
- start at 260px from top (as defined in CSS)
- 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>
精彩评论