我正在使用GSAP和IntersectionObserver来动画每一个滚动上的每个h1的字符。
一切似乎都在工作,但动画的opacity部分并没有像预期的那样工作。基本上,人们可以在转到opacity:0之前看到h1,然后返回到1(它让我想起了臭名昭著的无样式文本的Flash )。我使用的是.from方法。我希望每个h1在动画之前都是不可见的,但我不知道我做错了什么。请检查代码片段。
const titles = document.querySelectorAll("h1");
const options = {
root: null,
threshold: 0.25,
rootMargin: "-200px"
};
const observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
return;
}
entry.target.classList.add("anim-text");
// TEXT SPLITTING
const animTexts = document.querySelectorAll(".anim-text");
animTexts.forEach(text => {
const strText = text.textContent;
const splitText = strText.split("");
text.textContent = "";
splitText.forEach(item => {
text.innerHTML += "<span>" + item + "</span>";
});
});
// END TEXT SPLITTING
// TITLE ANIMATION
const charTl = gsap.timeline();
charTl.set("h1", { opacity: 1 }).from(
".anim-text span",
{
opacity: 0,
x: 40,
stagger: {
amount: 1
}
},
"+=0.5"
);
observer.unobserve(entry.target);
// END TITLE ANIMATION
});
}, options);
titles.forEach(title => {
observer.observe(title);
});* {
color: white;
padding: 0;
margin: 0;
}
.top {
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
height: 100vh;
width: 100%;
background-color: #279AF1;
}
h1 {
opacity: 0;
font-size: 4rem;
}
section {
padding: 2em;
height: 100vh;
}
.sec-1 {
background-color: #EA526F;
}
.sec-2 {
background-color: #23B5D3;
}
.sec-3 {
background-color: #F9C80E;
}
.sec-4 {
background-color: #662E9B;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.5/gsap.min.js"></script>
<div class="top">Scroll Down</div>
<section class="sec-1">
<h1>FIRST</h1>
</section>
<section class="sec-2">
<h1>SECOND</h1>
</section>
<section class="sec-3">
<h1>THIRD</h1>
</section>
<section class="sec-4">
<h1>FOURTH</h1>
</section>
非常感谢您的帮助!
发布于 2020-03-20 20:55:57
这实际上是由于JavaScript在页面加载之前等待运行而导致的未设置样式的内容(FOUC)的闪现。GreenSock实际上有我推荐的a tutorial on removing FOUC。
基本方法是使用CSS隐藏元素,并修改JS以使用更改后的CSS (例如将.from()更改为.to()或.fromTo())。您可以通过将h1 { opacity: 0 }添加到CSS,然后将以下代码添加到JS:gsap.set(h1, {opacity: 1});来完成此操作。
旁注: GSAP有自己的SplitText plugin,可以轻松地自定义文本的拆分方式(包括按行),处理非标准字符,并添加了轻松恢复为默认值的能力。如果你要拆分文本,我强烈建议你这样做!
https://stackoverflow.com/questions/60769635
复制相似问题