滚动上的动画元素没有响应



我有一个滚动动画工作在一个'测试'页面:https://wordpress-899937-3173615.cloudwaysapps.com/test/

问题是我不能使它在最终页面上工作,因为页面的高度不同,动画开始比预期的要早得多。

var scroll = document.querySelector ('.curve');
window.addEventListener ('scroll', function(){
var value =  1 + window.scrollY / -200;
scroll.style.transform = `scaleY(${value})`;
})
{
margin:0;
padding:0;
}
body {
height:200vh;
background-color:#111;

}
section {
position:absolute;
width:100%;
height:100%;
background:#ff2;

}
section .curve {
position:absolute;
bottom:-200px;
height:200px;
width:100%;
transform-origin:top;
}
section .curve img{
width:100%;
height:100%;

<body>
<section>
<span class = "curve">
<img src = "https://wordpress-899937-3173615.cloudwaysapps.com/wp-content/uploads/2023/01/curve-white-300x59.png">
</span>
</section>
</body>

我需要帮助改进代码,使其更"响应"任何页面高度。

如何触发动画从100%到0%的视口?

这可能适合您。我建议在单独的文件中进行测试,或者在JsFiddle上进行测试。我还建议你在不同的分辨率下测试一下,看看它是如何工作的。

提供的解决方案/建议使用一个修改版本的检查元素在DOM中的可见性,关于滚动和元素的位置,如这个SO答案所示。

var scroll = document.querySelector ('.curve');
var factor = scroll.getBoundingClientRect().top;
var value = 1;
window.addEventListener ('scroll', whiteCurve);
function whiteCurve() {
let scrollProperties = isScrolledIntoView(scroll);
if(scrollProperties["visible"]) {
value =  1 - window.scrollY  / factor;
if(value < 0) {
value = 0;
}
scroll.style.transform = `scaleY(${value})`;
} else {
// console.log('no');
}
}
function isScrolledIntoView(el) {
let rect = el.getBoundingClientRect();
let elemTop = rect.top;
let elemBottom = rect.bottom;
// Only completely visible elements return true:
//let isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
let isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return {
"visible" : isVisible,
"top" : elemTop,
"bottom" : elemBottom
};
}
* {
margin:0;
padding:0;
}
body {
height:200vh;
background-color: #111;
}
section {
position:absolute;
width:100%;
height:100%;
background:#ff2;
}
section .curve {
position:absolute;
bottom:-200px;
height:200px;
width:100%;
transform-origin:top;
}
section .curve img{
width:100%;
height:100%;
}
<section>
<span class="curve">
<img src="https://wordpress-899937-3173615.cloudwaysapps.com/wp-content/uploads/2023/01/curve-white-300x59.png">
</span>
</section>

在您的原始WordPress链接中,源代码包含一个固定值-750作为除数(并且您的初始尝试使用-200)。修改后的建议不再使用固定的数值,而是使用curve元素到页面顶部的初始距离(getBoundingClientRecT().top)。一旦curve元素变得部分可见(不像之前的建议,使用元素的完全可见性),这就开始发挥作用-随着scrollY的增加,比例因子减少,一旦到达顶部,scaleY变为零,给您想要的效果。

最新更新