繁体   English   中英

有没有一种方法可以使用 animate.style 在视口上显示 div 时进行动画处理

[英]Is there a way to animate when div is visible on viewport using animate.style

我只想在使用https://animate.style/在视口上可见 div 时为 div 设置动画

此时,即使它不在视口中,它也会为 div 设置动画,这是我正在使用的 animation 库的正常行为,但我希望 animation 在带有 class .box的 div 位于视口中时启动。 我添加了延迟,但这不切实际,因为我不确定用户何时会滚动到需要动画的网页部分

<div class="box animate__animated animate__fadeInLeft animate__delay-2s"><span>50 Years of Excellence and Beyond</span></div>

有没有一种方法可以仅当 div 在视口中时才开始动画,因为我不想使用 JS

代码笔: https://codepen.io/KGuide/pen/MWQaQWm

 .main{width:800px; height:250vh; background:blue; display:flex; align-items: flex-start; margin:auto auto;}.box {width:300px; height:300px; bottom::0; background:red; align-self: center;}
 <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet"/> <div class="main"> <div class="box animate__animated animate__fadeInLeft animate__delay-3s"><span>50 Years of Excellence and Beyond</span></div> </div>

动画风格

是一个 css animation 库,在滚动库上没有动画。 如果你想在滚动上制作动画,你应该使用AOSscrollmagiclax.js 之类的东西,javascript 和 jquery 中还有很多其他可用的东西。

由于我无法找到没有 JS 的解决方案,所以我最终使用以下代码来使用 JS 实现相同的效果。

当元素在视口中时,此代码添加和删除 animation class

$(document).ready(function () { 
//code to check if element is visible in viewport
               $.fn.isOnScreen = function () {
                   var win = $(window);
                   var viewport = {
                       top: win.scrollTop(),
                       left: win.scrollLeft()
                   };
                   viewport.right = viewport.left + win.width();
                   viewport.bottom = viewport.top + win.height();
                   var bounds = this.offset();
                   bounds.right = bounds.left + this.outerWidth();
                   bounds.bottom = bounds.top + this.outerHeight();
                   return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
               };

               $(window).scroll(function () {
                   if ($('.box').isOnScreen()) {
                       $(".box").addClass("animate__animated animate__fadeInLeft");
                   } else {
                       $(".box").removeClass("animate__animated animate__fadeInLeft").addClass("box");
                   }
               });
 });

我会让这个问题悬而未决,以防万一有人提出更好的轻量级解决方案。

暂无
暂无

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

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