首页 > 解决方案 > 滚动浏览彼此堆叠的 div

问题描述

长话短说:我想滚动浏览全屏 div。查看上一个问题,我发现这与我需要的非常接近,但有一些变化。 https://jsfiddle.net/naqk671s/

我不想让 div #1 固定并将 #2 放在它的顶部,我想让 #1 上升并显示 #2。

我对 jQuery 的信心不是很大,所以我试图改变一些值,但我只是把它弄得更糟。你认为有可能通过很少的改变来达到结果还是我应该从头开始?

under = function(){
    if ($window.scrollTop() < thisPos) {
        $this.css({
            position: 'absolute',
            top: ""
        });
        setPosition = over;
    }
};

over = function(){
    if (!($window.scrollTop() < thisPos)){
        $this.css({
            position: 'fixed',
            top: 0
        });
        setPosition = under;
    }
};

为了让我自己更清楚,我想要实现的基本上与我发布的小提琴相反。如果您一直向下滚动而不是开始向上滚动,那将是我想要达到的效果,但颠倒了。

提前致谢

标签: javascriptjqueryhtmlcss

解决方案



更新: 评论后,请求变得更加清晰,看看这些例子......


纯 CSS: https ://jsfiddle.net/9k8nfetb/


jQueryhttps ://jsfiddle.net/kajwhnc1/


另一个jQueryhttps ://jsfiddle.net/6da3e41f/


片段

var one = $('#one').offset().top;
var two = $('#two').offset().top;
var three = $('#three').offset().top;
var four = $('#four').offset().top;

$(window).scroll(function() {

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

  if (currentScroll >= 0) {
    $('#one').css({
      position: 'fixed',
      top: '0',
    });
  } else {
    $('#one').css({
      position: 'static'
    });
  }

  if (currentScroll >= two) {
    $('#two').css({
      position: 'fixed',
      top: '26px',
    });
  } else {
    $('#two').css({
      position: 'static'
    });
  }

  if (currentScroll >= three) {
    $('#three').css({
      position: 'fixed',
      top: '52px',
    });
  } else {
    $('#three').css({
      position: 'static'
    });
  }

  if (currentScroll >= four) {
    $('#four').css({
      position: 'fixed',
      top: '78px',
    });
  } else {
    $('#four').css({
      position: 'static'
    });
  }
});
body,
html {
  height: 200%;
}

#one,
#two,
#three,
#four {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: absolute;
}

#one {
  top: 0;
  background-color: aqua;
}

#two {
  top: 100%;
  background-color: red;
}

#three {
  top: 200%;
  background-color: #0a0;
}

#four {
  top: 300%;
  background-color: #a05;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<body>
  <div id="one">ONE</div>
  <div id="two">TWO TWO</div>
  <div id="three">THREE THREE THREE</div>
  <div id="four">FOUR FOUR FOUR FOUR</div>
</body>


推荐阅读