元素在视口中时的动画处理 [英] Animating elements when they are in the viewport

查看:137
本文介绍了元素在视口中时的动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在很多网站上都可以看到,当元素进入视口或距视口100像素等时,我想对元素进行处理.

As is seen on a lot of sites currently, I would like to do something with an element when it comes into the view port or 100px from the viewport etc.

我一直在寻找年龄,但到目前为止没有任何效果.

I have been searching for ages but so far nothing has worked.

我有一个元素列表,这些元素的高度为500px,宽度为100%.我对动画等以及我对它们的处理方式都没问题,只需要触发一些帮助即可,然后它们就会出现.

I have a list of elements which are 500px high and 100% width. Im okay with the animation etc and what Im going to do with them, just need a bit of help triggering then when they are coming into view.

我的目的是为元素提供一个动画元素类,然后能够使用该类检查其动画效果.

My aim is to give elements a class of animation-element and then be able to use that class to check if its in view.

伪代码:

$(window).on('scroll', function() {
    if (element is in the viewport) {
        $(this).doSomething();
    }
});

我似乎很懒,但是我一直在寻找太久而没有成功.

Seems lazy of me but I have been looking for too long without success.

任何以前的尝试总是在持续滚动时触发,因此即使元素不在视口中,而且我正在设置控制台日志,滚动一点点时我也会有100条日志.

Any previous attempts have just always triggered on when constant scrolling so even if the elements are no in the viewport and i'm setting a console log i'll have 100's of logs when scrolling a tiny bit.

推荐答案

我最近为另一个答案创建了类似的解决方案.

I have created a similar solution lately for another answer.

JS跟踪窗口的滚动,并与offset().top比较(窗口跟踪该元素距页面顶部的距离),比较窗口的滚动距离.如果窗口滚动条位于元素顶部的-300px范围内,则它将从左侧淡入/设置动画.

The JS tracks the scroll of the window, and compares how far the windows has scrolled, compared with the offset().top (Which tracks how far that element is from the top of the page). If the window scroll comes within -300px of the element top it fades/animates the animate in from the left.

JS:

var $win = $(window);
var $stat = $('.animation-element'); // Change this to affect your desired element.

$win.on('scroll', function () {
    var scrollTop = $win.scrollTop();

    $stat.each(function () {
        var $self = $(this);
        var prev=$self.offset();
        console.log(scrollTop);
        console.log(prev.top);
        if ( (scrollTop - prev.top) > -300) {
          $self.css('opacity', '1').addClass('animated fadeInLeft ');
        } else {
          console.log('n');
        }

    });

}).scroll();

这是工作中的JSfiddle-向下滚动以查看元素滑入. https://jsfiddle.net/wigster/5dbt7ft3/1/

Here's the working JSfiddle — scroll down to see elements slide in. https://jsfiddle.net/wigster/5dbt7ft3/1/

这篇关于元素在视口中时的动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆