纯CSS叠加滚动

3

只使用CSS和HTML,是否可能在滚动页面时将内部div(覆盖红色div)完全滚动掉,然后再滚动页面的其余部分? 基本上想知道是否只使用CSS可以冻结背景div并进行覆盖滚动? 然后,一旦红色div消失,解除背景滚动并继续进行。 类似于此网站: https://humaan.com/。还是需要使用某种JavaScript?

.headervideo{background-color:blue; width:100%; height:900px;}
.headerbreak{width:100%; height:300px;}

.headervideo #inner-box {
  background-color: red;
  height: 90%;
  width: 100%;
}
<div class="headervideo">
  <div id="inner-box"></div>
</div>

<div class="headerbreak">
<div>

2个回答

3

position:sticky 可以近似实现这个效果:

.headervideo {
  background: url(https://picsum.photos/id/1064/800/800) center/cover;
  height: 100vh;
  position: relative;
  z-index: 2;
}

.nextsection {
  background: url(https://picsum.photos/id/107/800/800) center/cover;
  height: 100vh;
  margin-top: -100vh;
  position: sticky;
  top: 0;
}

.container {
  height:200vh;
}

body {
  margin: 0;
}
<div class="container">
  <div class="headervideo"></div>

  <div class="nextsection"></div>
</div>

<div style="height:150vh"> more content later </div>


1
使用CSS,您可以使用hover事件来检测特定的滚动位置(例如在红色div后面的某个位置),但这在仅支持触摸的移动设备上无法工作。它也不可靠,因为光标可能位于屏幕的任何位置。
需要使用JavaScript来检测滚动位置。但是,您可以仅使用JavaScript在不同的滚动位置添加类,然后使用CSS完成其余部分。以下是一个简单的示例:

var red = document.querySelector('#inner-box');
var begin = red.scrollTop;
var end = begin + red.clientHeight;

console.log(begin)

document.body.classList.add('in');

window.addEventListener("scroll", (event) => {

  if(this.scrollY < begin) {
    document.body.classList.add('before');
    document.body.classList.remove('after');
    document.body.classList.remove('in');
  } else if(end < this.scrollY) {
    document.body.classList.remove('before');
    document.body.classList.add('after');
    document.body.classList.remove('in');
  } else {
    document.body.classList.remove('before');
    document.body.classList.remove('after');
    document.body.classList.add('in');
  };
});
.headervideo {
  background-color: blue;
  width: 100%;
  height: 900px;
}

.headerbreak {
  width: 100%;
  height: 300px;
}

.headervideo #inner-box {
  background-color: red;
  height: 90%;
  width: 100%;
}

body {
}

body.before {
  background-color: lightgreen;
}

body.in {
  background-color: lightpink;
}

body.after {
  background-color: lightblue;
}
<body>
  <div class="headervideo">
    <div id="inner-box"></div>
  </div>

  <div class="headerbreak">
    <div>
</body>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接