简体   繁体   English

Javascript视口淡入淡出

[英]Javascript Viewport Fade In Fade Out

I'm trying to accomplish something so simple it's painful, but I've yet to have luck after hours of work. 我正在尝试完成一些简单而痛苦的事情,但是经过数小时的工作我还没有走运。

I have 4 divs, each with the class '.slide'. 我有4个div,每个div都带有“ .slide”类。 All I want to do is have them invisible, but fade in when they are in the viewport. 我要做的就是使它们不可见,但是当它们在视口中时淡入。 If they leave the viewport, they should return to invisible. 如果它们离开视口,则应返回到不可见状态。 Any ideas? 有任何想法吗?

    $('.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/ http://jsfiddle.net/Agdax/3/

So i played a little and got this : 所以我玩了一点,得到了这个

/*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;
    };
}());

Animation is visible in modern browsers. 动画在现代浏览器中可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM