首页 > 解决方案 > 逐个面板滚动 – 固定然后滚动

问题描述

我试图让不同的部分重叠。当我滚动第 1 部分时,当它在窗口之外时,第 2 部分开始移动,依此类推。

与此示例类似: https ://wissenderkuenste.de/

到目前为止的代码:

HTML

<div id="section1" >
  // content    
</div>

<div id="section2" >
  // content    
</div>

CSS

#section1 {
  position: relative;
  background-color: darkgray;
  height: 500px;
}

#section2 {
  position: relative;
  top: -200px;
  background-color: pink;
  height: 500px;
}

Javascript

let sec1 = document.getElementById("section1");
let sec2 = document.getElementById("section2");

let sec1H = sec1.clientHeight;
let sec2H = sec2.clientHeight;

window.onscroll = function() {scroller()};

function scroller() {
  var winScrollDist = document.body.scrollTop ||  document.documentElement.scrollTop;
  var winHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;

  if (winScrollDist <= sec1H) {
    // sec1 inside view
    sec2.style.top = -200 + winScrollDist + "px";
  } else {
    // sec1 outside view
  }
}

这基本上是可行的,但是第 2 部分在闪烁(尤其是在 Safari 中),我猜是因为它正在逐个像素地向下移动。

有没有人达到类似的目标?

谢谢!

标签: javascripthtmlscroll

解决方案


这是更流畅的 CSS 代码。(JS 仅更改 DOM 的类)

但是此代码需要泛化以便于使用。

window.onscroll = function( event ) {
  let sec2 = document.getElementById("section2");
  let sec3 = document.getElementById("section3");
  if ( document.documentElement.scrollTop >= 850 - 75 ) {
  	if ( sec2.classList.contains( "pinned" ) ) {
      sec2.classList.add( "unpinned" );
      sec2.classList.remove( "pinned" );
    }
  }
  else {
  	if ( sec2.classList.contains( "unpinned" ) ) {
  	sec2.classList.add( "pinned" );
    sec2.classList.remove( "unpinned" );
    }
  }
  
  if ( document.documentElement.scrollTop >= 1700 - 150 ) {
  	if ( sec3.classList.contains( "pinned" ) ) {
      sec3.classList.add( "unpinned" );
      sec3.classList.remove( "pinned" );
    }
  }
  else {
  	if ( sec3.classList.contains( "unpinned" ) ) {
  	sec3.classList.add( "pinned" );
    sec3.classList.remove( "unpinned" );
    }
  }

};
* {
  box-sizing: border-box;
  position: relative;
  padding: 0;
  margin: 0;
  width: 100%;
}

body {
  height: 2500px;
}

#section1 {
  background-color: darkgray;
  height: 800px;
}

#section2 {
  background-color: pink;
  height: 800px;
}

#section3 {
  background-color: limegreen;
  height: 800px;
}

#section2.pinned {
  position: fixed;
  top: 75px;
}

#section2.unpinned {
  position: absolute;
  top: 850px;
}

#section3.pinned {
  position: fixed;
  top: 150px;
}

#section3.unpinned {
  position: absolute;
  top: 1700px;
}
<div id="section1" >
  // content 1
</div>

<div id="section2" class="pinned" >
  // content 2
</div>

<div id="section3" class="pinned">
  // content 3
</div>


推荐阅读