一旦它们在视口中可见,就为这些部分添加一个类

时间:2013-06-12 10:07:15

标签: javascript jquery scroll viewport

这就是我的尝试,但条件永远不会发生..

$(window).scroll(function(e){
            var scrollTop = $(window).scrollTop();
            var viewportHeight = $(window).height();
            $('section').each(function(){
                var top = $(this).offset().top;
                var bottom = top + $(this).height();
                if(top <= scrollTop && bottom >= (scrollTop + vieportHeight) ){
                    $(this).addClass('visible');
                    console.log('Hola');
                }else{
                    console.log(top,bottom,scrollTop,viewportHeight);
                }
            });
});

小提琴:http://jsfiddle.net/rYeMC/

我知道为什么我做错了?

4 个答案:

答案 0 :(得分:2)

除了拼写错误之外,您还有一个轻微的数学错误。我发现确定元素是否在屏幕上的最简单方法是确定视口的顶部和底部,并将其与元素的顶部和底部进行比较:

$(document).ready(function () {
    var viewport = $(window),
        setVisible = function (e) {
            var viewportTop = viewport.scrollTop(),
                viewportBottom = viewport.scrollTop() + viewport.height();
            $('section').each(function () {
                var self = $(this),
                    top = self.offset().top,
                    bottom = top + self.height(),
                    topOnScreen = top >= viewportTop && top <= viewportBottom,
                    bottomOnScreen = bottom >= viewportTop && bottom <= viewportBottom,
                    elemVisible = topOnScreen || bottomOnScreen;
                self.toggleClass('visible', elemVisible);
            });
        };
    viewport.scroll(setVisible);
    setVisible();
});

工作小提琴:http://jsfiddle.net/rYeMC/2/

答案 1 :(得分:0)

看起来像你想要的:

http://jsfiddle.net/rYeMC/1/

$(function () {
    $(window).scroll(function (e) {
        var scrollTop = $(window).scrollTop();
        var viewportHeight = $(window).height();
        $('section').each(function () {
            var top = $(this).offset().top;
            var bottom = top + $(this).height();
            if (top <= scrollTop && bottom >= (scrollTop + viewportHeight)) {
                $(this).addClass('visible');
            } else {
                console.log(top, bottom, scrollTop, viewportHeight);
                $(this).removeClass('visible');
            }
        });
    });
});

答案 2 :(得分:0)

你的代码一切都很好。只需更正拼写错误(视口)并注意,style属性会覆盖您的外部CSS!

答案 3 :(得分:0)

这是条件

if(scrollTop + viewportHeight >= top ){
    $(this).addClass('visible');
}