overlay.js
3.09 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Modal 覆盖层组件
*
* @author: Aiden Xu<aiden.xu@yoho.cn>
* @date: 2016/07/18
*/
'use strict';
const $ = require('yoho-jquery');
const ANIMATIONS = {
none: {
in: 'overlay-in',
out: 'overlay-out'
},
fade: {
in: 'overlay-fade-in',
out: 'overlay-fade-out'
}
};
class Overlay {
constructor(opts) {
this.isVisible = false;
// 默认参数
this.defaults = {
className: 'overlay',
clickToClose: true, // 点击关闭
onClose: $.noop, // 关闭回调函数
animation: 'fade', // 动画效果
disableScrolling: true // 是否禁止
};
// 初始化参数
this.settings = Object.assign({}, this.defaults, opts);
this.settings.animationClasses = {
in: ANIMATIONS[this.settings.animation].in,
out: ANIMATIONS[this.settings.animation].out
};
this.elem = $('<div/>', {
class: this.settings.className
});
// 点击关闭
this.elem.click(()=> {
if (this.settings.clickToClose) {
this.hide();
}
});
if (this.settings.disableScrolling) {
// 覆盖层出现时阻止滚动
$(window).on('touchmove', (e)=> {
if (this.isVisible) {
e.preventDefault();
}
});
}
}
_clearStylesClasses() {
this.elem
.removeClass(this.settings.animationClasses.in)
.removeClass(this.settings.animationClasses.out);
}
_cleanupListener() {
this.elem.css({
visibility: 'hidden'
});
this._clearStylesClasses();
this.isVisible = false;
this.elem.detach();
// 一次性监听,动画完成事件触发后删除监听器
this.elem[0].removeEventListener('webkitTransitionEnd', this._cleanupListener);
}
/**
* 显示覆盖层
*/
show() {
if (this.elem.parent().length === 0 && !this.isVisible) {
this.elem.appendTo('body');
this._clearStylesClasses();
this.elem.css({
visibility: 'visible'
}).show().addClass(this.settings.animationClasses.in);
if (this.settings.disableScrolling) {
$('body').css({
overflow: 'hidden'
});
}
this.isVisible = true;
}
}
/**
* 关闭覆盖层
*/
hide() {
if (this.isVisible) {
this._clearStylesClasses();
this.elem[0].addEventListener('webkitTransitionEnd', this._cleanupListener.bind(this));
this.elem.addClass(this.settings.animationClasses.out);
if (this.settings.disableScrolling) {
$('body').css({
overflow: 'auto'
});
}
setTimeout(()=> {
this._cleanupListener();
}, 100);
this.settings.onClose();
}
}
}
module.exports = Overlay;