简体   繁体   中英

Trigger CSS animation when it comes into viewport

I'm trying to make a border around a bootstrap 4 circular image. I want it to animate like the border in the codepen example below, but I want it to load when the user scrolls down. As I understand it I need to use Javascript to trigger it, but I'm not sure on how I can do that. Can someone help me?

https://codepen.io/katmai7/pen/jCAhv

<div class="wrap">
<div class="circle">
   <i class="icon i1 icon-terminal"></i>
   <i class="icon i2 icon-code-fork"></i>
   <i class="icon i3 icon-keyboard"></i>
   <i class="icon i4 icon-code"></i>
   <div class="line1"></div>
   <div class="line2"></div>
   <span class="text">hover on me</span>
 </div>
</div>

You can detect the scroll using

window.onscroll = function(e) {
    // Scroll up or down
}

The animation appears when

&:hover{
    animation: border .4s ease 1 forwards;
    cursor: none;
    [...]

So you'll need to add all that CSS to a new id and when you detect scroll add it to your element using JavaScript:

.newClass{
    animation: border .4s ease 1 forwards;
    cursor: none;
    [...]

Add it:

var element = document.getElementById("element-id");
element.className += " newClass";

The animation-fill-mode property specifies a style for the element when the animation is not playing (before it starts, after it ends, or both). CSS animations do not affect the element before the first keyframe is played or after the last keyframe is played.

You can use the new Intersection observer api https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API where a polyfill is available here: https://github.com/w3c/IntersectionObserver/tree/master/polyfill

the code would be something like this:

let options = {
root: document.querySelector('.wrap'),
rootMargin: '0px',
threshold: 1.0
}
let element = document.querySelector('.circle')
let observer = new IntersectionObserver(() => element.classList.add('onviewport') , options);

also you should modify your css to not listen on hover triggers but "respond" to a class : modifying

&:hover{

to

&.onviewport {

If you don't want to use the Intersection observer api you can use a plugin like this one https://github.com/imakewebthings/waypoints , the logic would still be similar.

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