向上滚动并向下滚动时,将类添加到视口Div

时间:2018-02-25 18:49:46

标签: javascript jquery

我使用以下代码在元素进入视口时添加类,并在视图离开视口时删除

function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = $(window).scrollTop() + $(window).height();

    $.each($animation_elements, function () {
        var $element = $(this);
        var element_height = $element.outerHeight();
        var element_top_position = $element.offset().top;
        var element_bottom_position = (element_top_position + element_height);
         if ((element_bottom_position <= window_bottom_position) && element_top_position >= window_top_position) {
            $element.addClass('blue');

        } else {
            $element.removeClass('blue');
        }

    });
}

它可以向上和向下滚动,但是现在我想添加不同的类来向上和向下滚动,我尝试下面的代码,但它似乎没有工作。

if((element_bottom_position <= window_bottom_position)) {
    $element.addClass('blue');
}
else if (element_top_position >= window_top_position) {
    $element.addClass('red');

} else {
    $element.removeClass('blue').removeClass('red');
}

1 个答案:

答案 0 :(得分:0)

您必须将scrollTop的值存储在函数之外,并比较函数内的scrollTop值,以检查它是否小于scrollTop的初始值,如THIS

您可以在代码中集成相同内容,如下所示:

>>> sms=['love', 'I', 'much', 'so', 'you']
>>> sorrend=[2,1,5,4,3]
>>> ' '.join(dict(sorted(zip(sorrend,sms))).values())
'I love you so much'
$(function(){

    var $animation_elements = $('.justlolo'),
    $window = $(window),
    scrollTop = $(window).scrollTop();
    
    function check_if_in_view() {
        var window_height = $(window).height();
        var window_top_position = $(window).scrollTop();
        var window_bottom_position = $(window).scrollTop() + $(window).height();
    
        $.each($animation_elements, function () {
            var $element = $(this);
            var element_height = $element.outerHeight();
            var element_top_position = $element.offset().top;
            var element_bottom_position = (element_top_position + element_height);
             if ((element_bottom_position > window_top_position) && element_top_position < window_bottom_position && window_top_position > scrollTop) {
                $element.removeClass('red').addClass('blue');
            } else if((element_bottom_position > window_top_position) && element_top_position < window_bottom_position && window_top_position < scrollTop) {
                $element.removeClass('blue').addClass('red');
            } else {
                $element.removeClass('blue red');                
            }
    
        });
    }
    
    $(window).on('scroll' , () => {
        check_if_in_view();
        scrollTop = $(window).scrollTop();
    })
    

});
*, *:after, *:before {
    box-sizing: border-box;
}

.justlolo {
  height: 70vh;
  background: #ccc
}

div:nth-of-type(even) {
 background: #eee;
 opacity: 0.8;
}

.blue {
  background: blue !important;
}

.red {
  background: red !important;
}