在某些滚动后使侧面div跟随

现在,右侧的div始终跟随滚动。 如果我希望它在页面滚动到div的顶部时开始跟随滚动,并使其在向上滚动时保持在那里,我还需要做什么?

的jsfiddle

$(window).scroll(function(){ var scrollTop = $(window).scrollTop(); $('.mSidebar').css( "top", scrollTop + 400 ); console.log(scrollTop); }); 

使用这样:

 $(document).ready(function(){ $(window).scroll(function(){ if($(document).scrollTop() > 400) { var newPos = $(document).scrollTop() + 400 ; $('.mSidebar').css( {top:newPos}); } else { $('.mSidebar').css( {top:400}); } }) }) 

使用position: fixed当您希望某些东西粘在顶部(或底部)时固定。

  //you can do it in initial layout, no need to set up css in js $('.mSidebar').css( "position", 'fixed'); //if user scrolled down more then 400 px we make div to stick to the top if (scrollTop>400) { $('.mSidebar').css( "top", 0); } else { //otherwise it stays in the middle of the screen $('.mSidebar').css( "top", '400px'); } 

https://jsfiddle.net/4zreh4ek/6/

您使用position:当滚动到达您选择的位置时固定。 这是由滚动事件触发的。

但! 确保div在返回<400滚动时重置。 这是我制定的一个例子。

希望这可以帮助!

 $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 400) { $('.mSidebar').css("position", "fixed"); $('.mSidebar').css("top", 5); } else { $('.mSidebar').css("position", "absolute"); $('.mSidebar').css("top", 400); } }); 
 .mSidebar { height: 300px; width: 200px; background-color: black; position: absolute; top: 400px; right: 20px; } body { width: 1000px; height: 10000px; }