javascript - 逐个面板滚动 – 固定然后滚动
问题描述
我试图让不同的部分重叠。当我滚动第 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 中),我猜是因为它正在逐个像素地向下移动。
有没有人达到类似的目标?
谢谢!
解决方案
这是更流畅的 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>
推荐阅读
- html - 如何在 HTML5 的不同纵横比下获得相似的结果?
- javascript - 在Javascript中获取未展平的过滤多维数组
- python - 我在 django 中的评论表格不起作用?它既不向数据库发送数据也不显示那些数据?
- networking - 关于 ipv4 和 ipv6
- reporting-services - 在新页面上显示列值,无论它是否已更改
- xml - 额外的价值“无”被打印出来,我不知道为什么
- zabbix - 为什么zabbix在我的Item中看不到Update Interval?
- hyperledger-fabric - 检查期间不可见交易的手动签名(结构 1.4)
- java-8 - Java8获取数据并保存在hashmap中,性能问题
- ios - 这两个调度队列有什么区别?