ljwrer / tricks

tricks
0 stars 0 forks source link

a scroll flow animation #2

Open ljwrer opened 7 years ago

ljwrer commented 7 years ago
/**
 * Created by Ray on 2017/2/14.
 */
const $ = require('jquery');
const _ = require('lodash');
class ScrollFlowAnimate {
    constructor($items = []) {
        this.$items = Array.from($items);
        this.$animateList = [];
        this.animating = false;
    }

    init() {
        this.$items.forEach(item => {
            const $item = $(item);
            $item.data('topDist', $item.offset().top + $item.outerHeight())
        });
        this.debounceScrollHandler = _.debounce(this.scrollHandler, 500).bind(this);
        this.debounceScrollHandler();
        $(window).on('scroll', this.debounceScrollHandler);
    }

    flow() {
        const $animateItem = $(this.$animateList.shift());
        this.animating = true;
        $animateItem.addClass('active');
        $animateItem.one('transitionend', () => {
            this.animating = false;
            if (this.$animateList.length > 0) {
                this.flow()
            }
        })
    }

    scrollHandler() {
        if (this.$items.length === 0) {
            $(window).off('scroll', this.scrollHandler)
            return false
        }
        const scrollTop = $(window).scrollTop() + $(window).height();
        this.$items = this.$items.filter(item => {
            const $item = $(item);
            if ($item.data('topDist') < scrollTop) {
                this.$animateList.push($item);
                return false
            }
            return true
        });
        if (!this.animating&&this.$animateList.length>0) {
            this.flow()
        }
    }
}
module.exports = ScrollFlowAnimate;