Javascript 视口淡入淡出



我正在尝试完成一些如此简单而痛苦的事情,但是经过几个小时的工作,我还没有运气。

我有 4 个div,每个div 都有".slide"类。 我想做的只是让它们不可见,但当它们在视口中时淡入。 如果它们离开视口,它们应返回到不可见状态。 有什么想法吗?

    $('.slide').waypoint(
    function() {
        if( $(this).is(":in-viewport") ) {
            $(this).animate({
                opacity: 1
            }, 100);
        }
        $('.slide').not(this).animate({
            opacity: 0
        }, 100);
    },
    {
        offset: function() {
            return $.waypoints('viewportHeight') - document.getElementById('navigation').clientHeight;
        }
    }
);

http://jsfiddle.net/Agdax/3/

所以我玩了一点,得到了这个:

/*jslint browser: true */
/*global $ */
(function () {
    'use strict';
    var invisibleClassName = 'invisible',
        scrollWait = 500;
    function isInvisible(el) {
        var wh = $(window).height(),
            wt = $(window).scrollTop(),
            eh = $(el).height(),
            et = $(el).offset().top;
        return ((wh + wt) <= et || wt >= (et + eh));
    }
    function checkVisibleAll(elements) {
        elements.each(function () {
            $(this)[(isInvisible(this) ? 'add' : 'remove') + 'Class'](invisibleClassName);
        });
    }
    $.fn.visible = function () {
        var elements = this,
            scrollTimer = null;
        // Don't check too often
        function scrolled() {
            clearTimeout(scrollTimer);
            scrollTimer = setTimeout(function () {
                checkVisibleAll(elements);
            }, scrollWait);
        }
        // Onload
        checkVisibleAll(elements);
        $(window).bind("scroll resize", scrolled);
        return this;
    };
}());

动画在现代浏览器中可见。

最新更新