我的代码工作,但问题是,访问者不能看到键入效果,因为它加载之前的视图



这段代码在viewport之前加载,因此动画对访问者是不可见的请帮助我加载这段代码时,文本来到视口。我在一个文本编辑器的元素或自定义CSS中使用这个,它工作得很好,但在页面加载时加载,而不是当访问者向下滚动查看页面的那一部分。

.css-typing p {
color: #5D5D5D; 
font-size: 95px;
margin: 10px 0 0 10px;
white-space: nowrap;
overflow: hidden;
width: 30em;
animation: type 4s steps(60, end); 
}

p:nth-child(2){
animation: type2 4s steps(60, end);
}
p:nth-child(3){
animation: type3 6s steps(60, end);
}

p:nth-child(4){
animation: type3 8s steps(60, end);
}

p:nth-child(5){
animation: type3 10s steps(60, end);
}

@keyframes type{ 
from { width: 0; } 
} 
@keyframes type2{
0%{width: 0;}
50%{width: 0;}
100%{ width: 100; } 
} 
@keyframes type3{
0%{width: 0;}
50%{width: 0;}
100%{ width: 100; } 
} 
@keyframes type4{
0%{width: 0;}
50%{width: 0;}
100%{ width: 100; } 
} 
@keyframes type5{
0%{width: 0;}
50%{width: 0;}
100%{ width: 100; } 
} 

动画没有做任何事情(至少在我的浏览器中,Edge/Windows10),因为宽度变化的参数没有任何单位-我认为%是想要的。

为了只在段落位于视口中时设置动画,我们可以使用intersectionObserver。这将告诉你元素何时进入和离开视口,在这些点上我们可以设置/取消动画设置。

我不清楚当有多个p元素时需要什么效果,所以这个片段只是在它们进入视口时将它们设置为动画,并在它们离开时停止动画。如果用户快速滚动,您可能希望研究动画延迟,以防止它们在彼此之间动画太快,或者您可能希望根据每个p元素有多少字符设置不同的时间。如果没有看到HTML和所需内容的进一步描述,就无法判断,但这段代码应该可以让您开始:

<style>
.filler {
height: 110vh;
}
.css-typing {
overflow: hidden;
}
.css-typing p{
color: #5D5D5D; 
font-size: 95px;
margin: 10px 0 0 10px;
white-space: nowrap;
overflow: hidden;
width: 30em;
animation: none 4s steps(60, end) 1; 
}
@keyframes type{ 
from { width: 0; } 
}
</style>
<body>
<div class="filler">PLEASE SCROLL DOWN</div>
<div class="css-typing">
<p>THIS IS SOME TEXT</p>
<p>Line 2</p>
<p>THIRD LINE</p>
<p>FOURTH LINE</p>
<div class="filler">MORE SCROLLING POSSIBLE</div>
</div>
<script>
const callback = (entries, observer) => {
entries.forEach(entry => {
entry.target.style.animationName = (entry.isIntersecting) ? 'type' : 'none';
});
};
const pEls = document.querySelectorAll('.css-typing p');
const observer = new IntersectionObserver(callback);
pEls.forEach( pEl => {
observer.observe(pEl, {threshold: 1.0});
}); 
</script>
</body>

相关内容

最新更新