简体   繁体   English

如何触发此动画在视口中启动一次?

[英]How can I trigger this animation to start once in viewport?

How can I trigger this animation to start once in viewport?如何触发此动画在视口中启动一次?

<div class="monster"></div>

.monster {
  width: 200px;
  height: 200px;
  margin: -50px auto;
  background: url('/wp-content/uploads/2021/07/sprite1.png') left center;
  animation: play 2.8s steps(15);
  animation-iteration-count: 1
}

@keyframes play {
    100% { background-position: -3000px; }
}

Use an IntersectionObserver in javascript to detect when the element is on screen, then trigger the class that plays the animation like this (I changed your animation values since you wouldn't see them in a SO snippet):在 javascript 中使用IntersectionObserver来检测元素何时出现在屏幕上,然后触发像这样播放动画的类(我更改了你的动画值,因为你不会在 SO 片段中看到它们):

 const element = document.querySelector('.monster'); const observer = new IntersectionObserver(entries => { element.classList.toggle( 'animation', entries[0].isIntersecting ); }); observer.observe( element );
 .monster { width: 200px; height: 200px; margin: 0 auto; background: black; } main { margin: 1000px auto; } @keyframes play { 100% { background: red; } } .animation { animation: play 2.8s steps(15); animation-iteration-count: 1; animation-fill-mode: forwards; } .monster:after { position: fixed; content: 'Keep scrolling!'; left: 50%; top: 50%; opacity: 0; transform: translate(-50%,-50%); transition: opacity .4s; } .monster:not(.animation):after { opacity: 1; }
 <main> <div class="monster"></div> </main>

Or maybe you can use a more traditional way.或者,也许您可​​以使用更传统的方式。

/* If Item is in Viewport */
function isInViewport(item) {

    var bounding = item.getBoundingClientRect(),
        myElementHeight = item.offsetHeight,
        myElementWidth = item.offsetWidth;

    if(bounding.top >= -myElementHeight
        && bounding.left >= -myElementWidth
        && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) + myElementWidth
        && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) + myElementHeight) {
        return true;
    } else {
        return false;
    }

}

Usage用法

var item = document.getElementsByClassName("monster");

if(isInViewport(item)) {
   item.classList.add("animation");
}

If you want to check it with scroll event如果你想用滚动事件检查它

const monster = document.getElementsByClassName("monster");

/* Window Scrolling */
window.addEventListener("scroll", function(){

   if(isInViewport(monster)) {
      monster.classList.add("animation"); 
   }

});

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

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