tab.js
2.34 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
/**
* Module: tab.js
*
* markup:
* <div class="tab">
* <ul class="tab-navs">
* <li class="tab-nav active">
* <a href="javascript:;" data-trigger="tab" data-target="#a"></a>
* </li>
* <li class="tab-nav">
* <a href="javascript:;" data-trigger="tab" data-target="#b"></a>
* </li>
* </ul>
* <div class="tab-panels">
* <div id="a" class="tab-panel">
* </div id="b" class="tab-panel">
* </div>
* </div>
*/
const $ = require('yoho-jquery');
let Tab = function(elem) {
this.$elem = $(elem);
};
Tab.prototype.show = function() {
let $nav = this.$elem;
let targetSelector = (function(elem) {
let selector = elem.dataset.target;
if (!selector) {
selector = elem.getAttribute('data-target') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
return selector;
}($nav[0]));
let $target = $(targetSelector);
if ($nav.hasClass('active') || $nav.parent().hasClass('active')) {
return;
}
function active($elem, $parent) {
$parent.children('.active').removeClass('active');
$elem.addClass('active');
}
active($nav.parent('.tab-nav'), $nav.closest('.tab-navs'));
active($target, $target.closest('.tab-panels'));
};
function Plugin(option) {
this.each(function() {
let $this = $(this);
let data = $this.data('yoho.tab');
let options = typeof option === 'object' && option;
if (!data) {
$this.data('yoho.tab', (data = new Tab(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
}
$.fn.yoTab = Plugin;
$.fn.yoTab.constructor = Tab;
$(document).on('click', '[data-trigger=tab]', function(event) {
let $nav = $(event.target);
let fun = '';
if ($nav.hasClass('active') || $nav.parent().hasClass('active')) {
return false;
}
$.each($nav.data(), function(index) {
if (index.substr(0, 3) === 'fun') {
fun = index.substr(3, index.length - 3);
if ($.isFunction(Tab.prototype[fun])) {
Plugin.call($nav, fun);
}
}
});
event.preventDefault();
event.stopPropagation();
Plugin.call($nav, 'show');
});
module.exports = Tab;