sticky.js 1.58 KB
/**
 *  Module: sticky
 *  Desc: 滚动固定
 *  @author: xuan.chen@yoho.cn
 */

'use strict';

const dataAPI = '[data-sticky]';

var Sticky = function(elem, options) {
    this.options = $.extend({}, Sticky.DEAFAULT, options);
    this.$elem = $(elem);
    this.$holder = $('<div></div>').height(this.$elem.height());
    this.$holder = this.$elem.wrap(this.$holder).parent();

    this.stickyState = null;


    this.$target = $(this.options.target)
        .on('scroll.yoho.sticky', $.proxy(this.checkPosition, this));

    this.checkPosition();
};

Sticky.DEAFAULT = {
    top: 0,     // offset top, 距离附着元素的位移
    target: window  // 附着元素
};

Sticky.prototype.checkPosition = function() {
    let options = this.options;

    if (!this.$elem.is(':visible')) {
        return;
    }

    let offsetTop = this.$holder.offset().top - options.top;
    let scrollTop = this.$target.scrollTop();

    let willSticky = scrollTop >= offsetTop;

    this.$elem.toggleClass('sticky', willSticky);
};


function Plugin(option) {
    this.each(function() {
        let $this = $(this);
        let data = $this.data('yoho.sticky');
        let options = typeof option === 'object' && option;

        if (!data) {
            $this.data('yoho.sticky', new Sticky($this, options));
        }

        if (typeof option === 'string') {
            $this[option]();
        }
    });
}

$.fn.Stricky = Plugin;
$.fn.Stricky.Constructor = Sticky;

window.onload = function() {
    $(dataAPI).each(function() {
        let $this = $(this);

        Plugin.call($this);
    });
};


module.exports = Sticky;