按面板滚动面板 - 固定然后滚动

时间:2018-04-24 13:07:11

标签: javascript html scroll

我试图让不同的部分重叠。当我滚动第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中),我猜是因为它逐个像素地向下移动。

有人做过类似的事吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这里有更流畅的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>