如何设置元素的高度以匹配缩放 div 的偏移速度?

How do I set the height of an element to match the offset speed of a scaling div?

我正在尝试设置元素的最大滚动,在本例中为 .contain,以匹配 .square 滚动时填充整个视口(宽度和高度)所需的高度.我需要弄清楚如何检索覆盖滚动偏移值所需的剩余高度。

这是一个显示当前发生情况的代码笔。卷轴到达底部,正方形无法填满屏幕。没有偏移量我可以让它完美地工作(见第 17 行),但我真的很想了解如何合并视差 offset/speed 效果。

https://codepen.io/anon/pen/zbeyQd


显示上述笔应该如何工作的非偏移版本。当滚动条到达底部时,正方形填满屏幕:https://codepen.io/anon/pen/Rdvvom

这应该可以解决问题

const sq = document.querySelector('.square')
const contain = document.querySelector('.contain')

//set desired scroll boundaries. can be any size
//the higher the value the longer you'll have to scroll
const scrollOffset = 250
const sqW = sq.offsetWidth
const sqH = sq.offsetHeight
const wHeight = window.innerHeight
const wWidth = window.innerWidth

contain.style.height = `${wHeight + scrollOffset}px`

window.addEventListener('scroll', (e) => {
  const percentScroll = window.scrollY * 100 / scrollOffset
  const width = (wWidth - sqW) * percentScroll / 100
  const height = (wHeight - sqH) * percentScroll / 100
  sq.style.width = `${sqW + width}px`
  sq.style.height = `${sqH + height}px`
})
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.contain {
  height: 100%;
  width: 100%;
  background-color: papayawhip;
}

.square {
  width: 100px;
  height: 100px;
  background-color: tomato;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.25;
}
<div class="contain">
    
  <div class="square"></div>

</div>