简体   繁体   中英

Make animations delay until in viewport?

I'm working on a site where intro text will be displayed based off time of day. It will switch between good morning, good evening, etc. I found a way using CSS to delay each word to fade in one by one. The issue is that the words are not in viewport right off the bad, so the animation is happening before the viewer sees it. How do I delay is until it's in viewport? Here is my current code including the CSS that made the animations enter one by one:

 var time = new Date().getHours(); if (time >= 1 && time <= 12) { document.getElementById("time").innerHTML = "<span>☀️</span> <span>Good</span> <span>Morning,</span> <span>Creative.</span>" } else if (time > 12 && time <= 17) { document.getElementById("time").innerHTML = "<span>☀️</span> <span>Good</span> <span>Afternoon,</span> <span>Creative.</span>" } else { document.getElementById("time").innerHTML = "<span>🌙</span> <span>Good</span> <span>Evening,</span> <span>Creative.</span>" }
 #time span { opacity: 0; transform: translateY(30px); animation: time 0.5s ease-out forwards; display: inline-block; } #time span:nth-of-type(2) { animation-delay: 0.5s; } #time span:nth-of-type(3) { animation-delay: 0.5s; } #time span:nth-of-type(4) { animation-delay: 1s; } @keyframes time { to { opacity: 1; transform: translateY(0); } }
 <h4 id="time">Hello Creative</h4>

Is there some way to clarify viewport in CSS? Or does this require JS? Thanks for any help!

Unfortunately there is no way to detect when something is in view with CSS. You should look into Intersection Observer API, then apply the animation CSS class when the item observed is in view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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