multiple divs with fixed position and scrolling

主宰稳场 提交于 2019-12-06 14:45:16

问题


I have 4 divs and I want to scroll down and cover all those divs. But... keeping the current div with fixed position on top of the browser

This is working great only scrolling down. But when I scroll up fails.

You can check this fiddle http://jsfiddle.net/rtSKj/ for a demo

This is the js code

$(document).ready(function() {
    $(window).scroll(function () {

        var scrollY = $(window).scrollTop();

        if(scrollY>=500){
            $('#block2').css({'position': 'fixed', 'margin-top': 0});
            $('#block3').css({'margin-top': '1000px'});
        }

        if(scrollY>=1000){
            $('#block3').css({'position': 'fixed', 'margin-top': 0});
            $('#block4').css({'margin-top': '1500px'});
        }

    });

});

note: the height of the divs is: 500px;

Should I consider the scroll direction to fix the behavior?


回答1:


You need to 'reset' the position and margin-top.

if(scrollY<500) {
  $('#block2').css({'position': 'relative', 'margin-top': '500px'});
}
if(scrollY<1000) {  
  $('#block3').css({'position': 'relative','margin-top': '1000px'});
}

See updated fiddle: http://jsfiddle.net/rtSKj/14/



来源:https://stackoverflow.com/questions/14653602/multiple-divs-with-fixed-position-and-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!