【问题标题】:Fade in elements when they come into viewport元素进入视口时淡入淡出
【发布时间】:2015-10-31 13:10:15
【问题描述】:

每当这些元素进入视野时,我都会尝试使用“fade-me”类淡入元素。我找到了这个小提琴:http://jsfiddle.net/tcloninger/e5qad/,它确实做到了这一点,但是它重复地将不透明度值添加到出现的元素中。如果我尝试使用 Velocity 的过渡 slideUpIn 而不是不透明度,这将创建一个循环动画。所以我有以下代码:

$(document).ready(function() {

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        /* Check the location of each desired element */
        $('.hideme').each( function(i){

            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){

                $(this).velocity('transition.slideUpIn', { stagger: 700 }).delay(1000)     
            }
        }); 
    });
});

它可以工作,但它会循环 SlideUpIn 动画。如何让它在出现的那个元素上只运行一次动画?

【问题讨论】:

    标签: javascript jquery html velocity.js


    【解决方案1】:

    切换一个 CSS 类作为指示器,然后检查它:

    var $window = $(window);
    var $doc = $(document);
    var $hideMe = $('.hideme');
    
    $doc.ready(function () {
    
        $window.scroll(function () {
            var bottom_of_window = $window.scrollTop() + $window.height();
    
            $hideMe.each(function (i) {
                var $elm = $hideMe.eq(i);
                var bottom_of_object = $elm.offset().top + $elm.outerHeight();
    
                if (bottom_of_window > bottom_of_object) {
                    if (!$elm.hasClass('in-viewport')) {
                        $elm.addClass('in-viewport');
                        $elm.velocity('transition.slideUpIn', { stagger: 700 }).delay(1000);
                    }
                } else {
                    $elm.removeClass('in-viewport');
                }
            }); 
    
        });
    
    });
    

    【讨论】:

    • 这很好用,谢谢。如何在每个元素上仅触发一次该功能?因此,如果该元素在某个时候出现,则该函数不应再次在其上运行。
    • 去掉最后一个else { ... }就不会再触发了。
    猜你喜欢
    • 2023-04-09
    • 2014-03-19
    • 2017-06-10
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2011-07-14
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多