具有固定位置和滚动的多个div [英] multiple divs with fixed position and scrolling

查看:119
本文介绍了具有固定位置和滚动的多个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个div,我想向下滚动并覆盖所有这些div.但是...将当前div保持固定位置在浏览器顶部

仅向下滚动,效果很好.但是当我向上滚动时失败.

您可以在 http://jsfiddle.net/rtSKj/上查看该提琴. >

这是js代码

$(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'});
        }

    });

});

注意:div的高度为:500px;

我应该考虑滚动方向来解决此问题吗?

解决方案

您需要重置"位置和边距顶部.

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

请参阅更新的提琴: http://jsfiddle.net/rtSKj/14/

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?

解决方案

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/

这篇关于具有固定位置和滚动的多个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆