简体   繁体   English

滚动动画(仅动画一次)

[英]Animation on scroll (only animate once)

So I have an "active" tag that is set to be added to elements with the class "reveal" when they are in the viewport.所以我有一个“活动”标签,当它们在视口中时,它被设置为添加到具有“显示”类的元素中。 But after I scroll down the class "active" is now removed.但是在我向下滚动后,“活动”类现在被删除了。 How do I make it so that when "active" is first applied it does not get removed again.我如何做到这一点,以便在第一次应用“活动”时它不会再次被删除。 Below is the JavaScript that adds the "active" class.下面是添加“活动”类的 JavaScript。

 function reveal() { var reveals = document.querySelectorAll(".reveal"); for (var i = 0; i < reveals.length; i++) { var windowHeight = window.innerHeight; var elementTop = reveals[i].getBoundingClientRect().top; var elementVisible = 20; if (elementTop < windowHeight - elementVisible) { reveals[i].classList.add("active"); } else { reveals[i].classList.remove("active"); } } } window.addEventListener("scroll", reveal);

Welcome to StackOverflow.欢迎来到 StackOverflow。 You are using if else condition which is not required here.您正在使用此处不需要的 if else 条件。 Just using a if block inside loop will do the work.只需在循环内使用 if 块即可完成工作。 Please see below code:请看下面的代码:

 function reveal() { var reveals = document.querySelectorAll(".reveal"); for (var i = 0; i < reveals.length; i++) { var windowHeight = window.innerHeight; var elementTop = reveals[i].getBoundingClientRect().top; var elementVisible = 20; if (elementTop < windowHeight - elementVisible) { reveals[i].classList.add("active"); } /* Not needed else { reveals[i].classList.remove("active"); } */ } } window.addEventListener("scroll", reveal);

I have commented else block so it is not executed.我已经评论了 else 块,所以它没有被执行。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM