如何在js中双向滚动动画(顶部/底部)



我使用绑定客户端在JS中创建了一个小的aniamtion。一旦我向下滚动直到文本/内容出现,我就通过应用"将其不透明度更改为1;。活动的";来自CSS。当我再次在元素上方向上滚动时,不透明度变回0(因为".active"被取消(。

问题是,当我从下面向上滚动到内容元素时,我想做同样的事情。一旦用户进入内容元素下方,不透明度应为0,然后当他们向上滚动时(因此内容元素再次出现在视图中(,不透明度应该为1。因此,它使动画双向运行,就像在scrollrevealjs的首页上一样。

document.addEventListener('scroll',()=>{
let content = document.querySelector('.text');
let contentPositiontop = content.getBoundingClientRect().top;
let screenPosition = window.innerHeight ;
if (contentPositiontop < screenPosition){   
content.classList.add('active');                                                                
}
else{
content.classList.remove('active');
}
});
.text{
transform: translateX(700px) translateY(1000px);
font-family: Inter;
font-weight: 800;
font-size: 40px;
opacity: 0;
transition: all 2s ease;
position: absolute;
}
.active{
opacity: 1;
}

您只需要检查内容元素底部和顶部的高度

(对于顶部,我们需要添加屏幕高度(window.innerHeight(,因为我们正在将其位置与屏幕底部进行比较。我们不需要将其放在底部,因为我们正在将其位置与屏幕顶部进行比较,屏幕顶部的垂直位置为0。(

当底部和顶部都在范围内时,我们显示内容元素

(如果由于某种原因,内容元素的高度大于屏幕的高度,则必须选择0和window.innerHeight之间的值来触发转换。(

document.addEventListener('scroll',() => {
const
content = document.querySelector('.text'),
top = content.getBoundingClientRect().top,
bottom = content.getBoundingClientRect().bottom;
if (top < innerHeight && bottom > 0){
content.classList.add('active');
}
else{
content.classList.remove('active');
}
});
.spacer{ height: 104vh; }
.text{ height: 100vh; background: blue; transform: translateX(20px); opacity: 0; transition: all 2s ease; }
.active{ opacity: 1; }
<div class="spacer"> </div>
<div class="text"></div>
<div class="spacer"> </div>
.

最新更新