反向滚动显示脚本

时间:2015-04-03 16:02:23

标签: jquery

我有一个简单的时间轴,在滚动页面时显示信息块。向下滚动时,元素从每一侧反弹。现在,元素在加载时仍保持可见但我希望它们在不在视图中时隐藏,并在我滚动到顶部时以相同的方式重新显示......

如何修改"反向"?中的代码? 谢谢你的帮助。

这是我使用的代码:

jQuery(document).ready(function($){
var $timeline_block = $('.cd-timeline-block');

//hide timeline blocks which are outside the viewport
$timeline_block.each(function(){
    if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.75) {
        $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
    }
});

//on scolling, show/animate timeline blocks when enter the viewport
$(window).on('scroll', function(){
    $timeline_block.each(function(){
        if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.75 && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) {
            $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
        }
    });
});
});

3 个答案:

答案 0 :(得分:1)

你已经有了基本的语句,只需将行为汇总到一个函数中,并在页面加载时调用该函数一次。

function onScroll() {
  $('.cd-timeline-block').each( function() {
    if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.75 && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) {
      $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
    } else {
      $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden').removeClass('bounce-in');
    }
  });
};

$(window).scroll(onScroll);
$(onScroll);  // shorthand for $(document).ready(onScroll);

答案 1 :(得分:0)

隐藏课程时,您需要删除bounce-in课程。否则,当您显示它并添加bounce-in类元素已经拥有它时,动画将不再运行。

对于您的视口功能:

$timeline_block.each(function(){
    if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.75) {
        var $block = $(this).find('.cd-timeline-img, .cd-timeline-content');
        $block.addClass('is-hidden');
        $block.removeClass('bounce-in');
    }
});

答案 2 :(得分:0)

根据Travis的回答,我添加了一个 else if 语句。值得添加一个类似“反弹”的课程。因为它隐藏时不太光滑。

  function onScroll() {
  $('.cd-timeline-block').each( function() {
    if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.75 && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) {
      $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
    } else if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.75) {
      $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden').removeClass('bounce-in');
    }
  });
};

$(window).scroll(onScroll);
$(onScroll);  // shorthand for $(document).ready(onScroll);