2 个带有固定图像的 div,可响应滚动



我正在尝试创建一个包含 2 个div 和 2 个图像的滚动动画。 由于缺乏更好的解释(正如您可能从标题中猜到的那样(,我制作了一个快速动画来展示我想要实现的目标。

这是我之前制作的托管版本。我试图在视差滚动的帮助下创建效果,但这不是我想要的。 这是一个 Zeit Now 部署,因此您可以将/_src 附加到 url 并查看源代码。

现在我不确定这是否是创建动画的正确方法,老实说,我不知道任何其他方法可以解决这个问题。 因此,我并不是要求一个没有任何缺陷的完整答案(尽管将不胜感激(,而是朝着正确的方向推动。

快速完成,因此可能存在一些问题,我试图以某种方式使变量通用,以便您可以玩东西(检查此小提琴(

const body = document.body,
html = document.documentElement;
const targetImg = document.querySelector('.second');
// our image's initial height
const imgHeight = targetImg.clientHeight;
// the final value for image height (at scroll end)
const imgTargetHeight = 0;
// total height of our document
const totalHeight = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// visible window height
const windowHeight = window.innerHeight;
// starting scroll position we want to start calculations from (at this point and before, our image's height should equal its initial height 'imgHeight')
const fromScroll = 0;
// final scroll position (at this point and after, our image's height should equal 'imgTargetHeight')
const toScroll = totalHeight - windowHeight;
window.addEventListener('scroll', function() {
// get current scroll position, these multiple ORs are just to account for browser inconsistencies.
let scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
// force the scroll position value used in our calculation to be between 'fromScroll` and 'toScroll'
// In this example this won't have any 
// effect since fromScroll is 0 and toScroll is the final possible scroll position 'totalHeight - windowHeight',
// but they don't have to be, try setting fromScroll = 100 and toScroll = totalHeight - windowHeight - 100  for example to see the difference.
// the next line is just a shorthand for:
// if (scrollPos <= fromScroll) {
//   scrollPos = fromScroll;
// } else if (scrollPos >= toScroll) {
//   scrollPos = toScroll;
// } else {
//   scrollPos = scrollPos;
// }
scrollPos = scrollPos <= fromScroll ? fromScroll : (scrollPos >= toScroll ? toScroll : scrollPos);
// our main calculation, how much should we add to the initial image height at our current scroll position.
const value = (imgTargetHeight - imgHeight) * (scrollPos - fromScroll) / (toScroll - fromScroll);
targetImg.style.height = imgHeight + value + "px";
});
.container {
height: 200vh;
}
.img-container {
position: fixed;
width: 100vw;
height: 100vh;
text-align: center;
background: white;
overflow: hidden;
}
.second {
background: tomato;
}
img {
position: absolute;
left: 50vw;
top: 50vh;
transform: translate(-50%, -50%);
}
<div class="container">
<div class="img-container first">
<img src="https://fixedscrollingtest-takidbrplw.now.sh/luigi.png" alt="">
</div>
<div class="img-container second">
<img src="https://fixedscrollingtest-takidbrplw.now.sh/mario.png" alt="">
</div>
</div>

最新更新