Blame view

public/js/plugin/sticky.js 1.58 KB
陈轩 authored
1 2 3 4 5 6 7 8
/**
 *  Module: sticky
 *  Desc: 滚动固定
 *  @author: xuan.chen@yoho.cn
 */

'use strict';
陈轩 authored
9 10
const dataAPI = '[data-sticky]';
lijing authored
11
let Sticky = function(elem, options) {
陈轩 authored
12 13 14
    this.options = $.extend({}, Sticky.DEAFAULT, options);
    this.$elem = $(elem);
    this.$holder = $('<div></div>').height(this.$elem.height());
陈轩 authored
15 16 17 18 19
    this.$holder = this.$elem.wrap(this.$holder).parent();

    this.stickyState = null;

陈轩 authored
20 21 22 23 24 25 26
    this.$target = $(this.options.target)
        .on('scroll.yoho.sticky', $.proxy(this.checkPosition, this));

    this.checkPosition();
};

Sticky.DEAFAULT = {
毕凯 authored
27 28
    top: 0, // offset top, 距离附着元素的位移
    target: window // 附着元素
陈轩 authored
29 30 31
};

Sticky.prototype.checkPosition = function() {
陈轩 authored
32 33 34
    let options = this.options;

    if (!this.$elem.is(':visible')) {
陈轩 authored
35 36
        return;
    }
陈轩 authored
37 38 39 40 41 42 43

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

    let willSticky = scrollTop >= offsetTop;

    this.$elem.toggleClass('sticky', willSticky);
陈轩 authored
44 45 46
};

陈轩 authored
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
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);
    });
};
陈轩 authored
74 75

module.exports = Sticky;