sticky.js
1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
74
75
/**
* 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;