jQuery 当内容滚动到视图中时激活 CSS3 动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16325679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:56:19  来源:igfitidea点击:

Activate CSS3 animation when the content scrolls into view

jqueryhtmlcssscrollcss-animations

提问by Kevin Jung

I have a bar chart that animates with CSS3 and the animation currently activates as the page loads.

我有一个使用 CSS3 制作动画的条形图,当前动画在页面加载时激活。

The problem I have is that the given bar chart is placed off screen due to lots of content before it so by the time a user scrolls down to it, the animation has already finished.

我遇到的问题是给定的条形图由于前面有很多内容而被放置在屏幕外,因此当用户向下滚动到它时,动画已经完成。

I was looking for ways either through CSS3 or jQuery to only activate the CSS3 animation on the bar chart when the viewer sees the chart.

我一直在寻找通过 CSS3 或 jQuery 仅在查看者看到图表时激活条形图上的 CSS3 动画的方法。

<div>lots of content here, it fills the height of the screen and then some</div>
<div>animating bar chat here</div>

If you scroll down really fast right after page load, you can see it animating.

如果您在页面加载后立即快速向下滚动,您可以看到它的动画效果。

Here is a jsfiddleof my code. Also, I dont know if this matters, but I have several instances of this bar chart on the page.

这是我的代码的jsfiddle。另外,我不知道这是否重要,但我在页面上有几个此条形图的实例。

I have come across a jQuery plug-in called waypoint but I had absolutely no luck getting it to work.

我遇到了一个名为 waypoint 的 jQuery 插件,但我绝对没有让它工作的运气。

If someone could point me in the right direction, it would be really helpful.

如果有人能指出我正确的方向,那将非常有帮助。

Thanks!

谢谢!

回答by Matt Coughlin

Capture scroll events

捕获滚动​​事件

This requires using JavaScript or jQuery to capture scroll events, checking each time a scroll event fires to see if the element is in view.

这需要使用 JavaScript 或 jQuery 来捕获滚动事件,在每次触发滚动事件时检查元素是否在视图中。

Once the element is in view, start the animation. In the code below, this is done by adding a "start" class to the element, that triggers the animation.

一旦元素在视图中,开始动画。在下面的代码中,这是通过向元素添加一个“开始”类来完成的,它会触发动画。

Updated demo

更新演示

HTML

HTML

<div class="bar">
    <div class="level eighty">80%</div>
</div>

CSS

CSS

.eighty.start {
    width: 0px;
    background: #aae0aa;
    -webkit-animation: eighty 2s ease-out forwards;
       -moz-animation: eighty 2s ease-out forwards;
        -ms-animation: eighty 2s ease-out forwards;
         -o-animation: eighty 2s ease-out forwards;
            animation: eighty 2s ease-out forwards;
}

jQuery

jQuery

function isElementInViewport(elem) {
    var $elem = $(elem);

    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round( $elem.offset().top );
    var elemBottom = elemTop + $elem.height();

    return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {
    var $elem = $('.bar .level');

    // If the animation has already been started
    if ($elem.hasClass('start')) return;

    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('start');
    }
}

// Capture scroll events
$(window).scroll(function(){
    checkAnimation();
});

回答by Nico Napoli

Sometimes you need the animation to always occur when the element is in the viewport. If this is your case, I slightly modified Matt jsfiddlecode to reflect this.

有时您需要动画始终在元素位于视口中时发生。如果这是您的情况,我稍微修改了 Matt jsfiddle代码以反映这一点。

jQuery

jQuery

// Check if it's time to start the animation.
function checkAnimation() {
    var $elem = $('.bar .level');

    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('start');
    } else {
        $elem.removeClass('start');
    }
}

回答by Wtower

In order to activate a CSS animation, a class needs to be added to the element when this becomes visible. As other answers have indicated, JS is required for this and Waypointsis a JS script that can be used.

为了激活 CSS 动画,需要在元素可见时向元素添加一个类。正如其他答案所指出的,这需要 JS,而Waypoints是一个可以使用的 JS 脚本。

Waypoints is the easiest way to trigger a function when you scroll to an element.

当您滚动到一个元素时,航点是触发功能的最简单方法。

Up to Waypoints version 2, this used to be a relatively simple jquery plugin. In version 3 and above (this guide version 3.1.1) several features have been introduced. In order to accomplish the above with this, the 'inview shortcut'of the script can be used:

直到 Waypoints 版本 2,这曾经是一个相对简单的 jquery 插件。在版本 3 及更高版本(本指南版本 3.1.1)中,引入了多项功能。为了通过此完成上述操作,可以使用脚本的“查看快捷方式”

  1. Download and add the script files from this linkor from Github(version 3 is not yet availablethrough CDNJS, although RawGitis always an option too).

  2. Add the script to your HTML as usual.

    <script src="/path/to/lib/jquery.waypoints.min.js"></script>
    <script src="/path/to/shortcuts/inview.min.js"></script>
    
  3. Add the following JS code, replacing #myelementwith the appropriate HTML element jQuery selector:

    $(window).load(function () {
        var in_view = new Waypoint.Inview({
            element: $('#myelement')[0],
            enter: function() {
                $('#myelement').addClass('start');
            },
            exit: function() {  // optionally
                $('#myelement').removeClass('start');
            }
        });
    });
    
  1. 从此链接Github下载并添加脚本文件(版本 3不能通过CDNJS 获得,尽管RawGit也始终是一个选项)。

  2. 像往常一样将脚本添加到 HTML 中。

    <script src="/path/to/lib/jquery.waypoints.min.js"></script>
    <script src="/path/to/shortcuts/inview.min.js"></script>
    
  3. 添加以下 JS 代码,替换#myelement为相应的 HTML 元素 jQuery 选择器:

    $(window).load(function () {
        var in_view = new Waypoint.Inview({
            element: $('#myelement')[0],
            enter: function() {
                $('#myelement').addClass('start');
            },
            exit: function() {  // optionally
                $('#myelement').removeClass('start');
            }
        });
    });
    

We use $(window).load()for reasons explained here.

我们使用这里$(window).load()解释的原因。

Updated Matt's fiddle here.

在这里更新了马特的小提琴。

回答by Spongebob Comrade

In addition to these answers please consider these points :

1- Checking the element in view has many considerations :
How to tell if a DOM element is visible in the current viewport?

除了这些答案,请考虑以下几点:

1- 检查视图中的元素有很多注意事项:
如何判断 DOM 元素在当前视口中是否可见?

2- If someone wanted to have more control over the animation (e.g. set "the animation type" and "start delay") here is a good article about it :
http://blog.webbb.be/trigger-css-animation-scroll/

2-如果有人想对动画有更多的控制(例如设置“动画类型”和“开始延迟”),这里有一篇关于它的好文章:http:
//blog.webbb.be/trigger-css-animation-滚动/

3- And also it seems that calling addClasswithout a delay (using setTimeout) is not effective.

3- 而且似乎没有延迟地调用addClass(使用setTimeout)是无效的。

回答by Sanya Kravchuk

CSS FOR TRIGGER :

触发器的 CSS :

<style>
    .trigger{
      width: 100px;
      height: 2px;
      position: fixed;
      top: 20%;
      left: 0;
      background: red;
      opacity: 0;
      z-index: -1;
    }
</style>
<script>
        $('body').append('<div class="trigger js-trigger"></div>');

        $(document).scroll(function () {

           $('YOUR SECTIONS NAME').each(function () {

               let $this = $(this);

               if($this.offset().top <= $('.js-trigger').offset().top) {

                   if (!$this.hasClass('CLASS NAME FOR CHECK ACTIVE SECTION')) {
                       $this
                           .addClass('currSec')
                           .siblings()
                           .removeClass('currSec'); 
                   }
               }

           });

        });
</script>