gpt4 book ai didi

css 动画在滚动时发生,而不是在页面加载时发生

转载 作者:太空狗 更新时间:2023-10-29 12:29:51 28 4
gpt4 key购买 nike

我的 css 动画有问题,看起来动画是在页面加载后而不是在您滚动到该部分时发生的,我如何让我的动画在您滚动到该部分而不是在页面加载后发生?

这是我的样式元素:

.slick-slide:nth-child(odd) {
-webkit-animation-name: fadeInLeft;
-moz-animation-name: fadeInLeft;
-o-animation-name: fadeInLeft;
animation-name: fadeInLeft;
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
-o-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-delay: 1s;
-moz-animation-delay: 1s;
-o-animation-duration:1s;
animation-delay: 1s;
}

这是我的关键帧

@-webkit-keyframes fadeInLeft {
from {
opacity:0;
-webkit-transform: translatex(-10px);
-moz-transform: translatex(-10px);
-o-transform: translatex(-10px);
transform: translatex(-10px);
}
to {
opacity:1;
-webkit-transform: translatex(0);
-moz-transform: translatex(0);
-o-transform: translatex(0);
transform: translatex(0);
}
}
@-moz-keyframes fadeInLeft {
from {
opacity:0;
-webkit-transform: translatex(-10px);
-moz-transform: translatex(-10px);
-o-transform: translatex(-10px);
transform: translatex(-10px);
}
to {
opacity:1;
-webkit-transform: translatex(0);
-moz-transform: translatex(0);
-o-transform: translatex(0);
transform: translatex(0);
}
}
@keyframes fadeInLeft {
from {
opacity:0;
-webkit-transform: translatex(-100px);
-moz-transform: translatex(-100px);
-o-transform: translatex(-100px);
transform: translatex(-100px);
}
to {
opacity:1;
-webkit-transform: translatex(0);
-moz-transform: translatex(0);
-o-transform: translatex(0);
transform: translatex(0);
}
}

最佳答案

在纯 CSS 中无法让事物感知滚动。当元素进入 View 时,您将不得不使用 JavaScript 添加一个类。

一种方法是使用 Intersection Observer API (如果您需要与旧浏览器兼容,可以在线使用 polyfill)。

let observer = new IntersectionObserver(updates => {
updates.forEach(update => {
if (update.isIntersecting) {
update.target.classList.add('visible');
} else {
update.target.classList.remove('visible');
}
});
}, { threshold: 0 });

[...document.querySelectorAll('.element')].forEach(element => observer.observe(element));

注意:如果你的动画让你的元素完全离开屏幕的一侧,这个方法将不起作用(或者至少需要一些调整),因为它要么永远不会与视口(viewport)相交,要么在之前触发反向动画结束。

JSFiddle example

关于css 动画在滚动时发生,而不是在页面加载时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815237/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com