我原来用Prototype.js写过几篇关于
选项卡(Tabs)的日志,还用这个实例说明了一下
Prototype.js的继承方式。前阵子回过头看看,发现当初的程序有很大的不足,最主要的是将前台XHTML代码的DOM结构写进了JS代码,未能实现XHTML和JS的解耦,通用性大大降低,
这阵子看了看Mootools.js,在《Mootools Essential》书里最后的实例也是用选项卡做为实例讲解了Mootools.js的应用,并也讲解了Mootools的继承。于是,我又萌生了在此基础上继续下去的想法,借此机会来熟悉Mootools的开发方式。
选项卡的核心思想是通过与标签交互来显示相应的内容,因此,选项标签与选项内容页应该为两个数组,首先列出来的是XHTML的代码,我用两个UL来实现选项标签和选项内容页:
Code
1
<div class="divide">
2
<ul id="tabs" class="tabs">
3
<li>Tab 1</li>
4
<li>Tab 2</li>
5
<li>Tab 3</li>
6
<li>Tab 4</li>
7
</ul>
8
<ul id="sections" class="sections">
9
<li>This is the content for the first tab.</li>
10
<li>This is the content for the second tab.</li>
11
<li>This is the content for the third tab.</li>
12
<li>This is the content for the fourth tab.</li>
13
</ul>
14
</div>
接下来要构思的是程序实现,编程思路是,记录当前所显示标签的下标,当触发标签事件时,如果产生事件的标签下标与当前记录相同,则不做动作,如果不同,则隐藏原来的标签,显示当前的标签,同时记录下当前下标。
在程序初始化时,通过传入选项标签与选项内容页的数组来实现Tabs类与前端DOM结构的解耦,并通过第三个对象参数来设定选项卡的可选式参数。可选式参数包括设定与标签交互的鼠标行为(mouseEvent),当前所选标签的CSS(selectedTabCss)及当前内容页的CSS(selectedSectionCss),还有一个是第一个要显示的内容(firstShow)。
程序内部结构,我分为几个内部函数来组成,包括显示选项内容(showSection),隐藏选项内容(hideSection),选项内容的显隐(toggleSection),选项标签要绑定的事件(tabEvent),还有两个函数实现选项卡实例化时DOM的初始显示(render)以及将事件绑定至选项标签(attach)。
代码很简单,如下:
Code
1
var Tabs = new Class(
{
2
3
Implements: [Options,Events],
4
5
options:
{
6
selectedTabCss:'selected',
7
selectedSectionCss:'selected',
8
firstShow:0,
9
mouseEvent:'click'
10
},
11
12
initialize:function(tabs, sections, options)
{
13
this.setOptions(options);
14
this.current = this.options.firstShow;
15
this.tabs = $$(tabs);
16
this.sections = $$(sections);
17
this.sectionsLength = $$(sections).length;
18
this.attach();
19
this.render();
20
},
21
22
render:function()
{
23
this.sections.each(function(section, index)
{
24
if( index !== this.current )
{
25
section.hide();
26
}else
{
27
this.showSection(index);
28
};
29
}, this);
30
},
31
32
attach:function()
{
33
this.tabs.each(function(tab, index)
{
34
tab.addEvent(this.options.mouseEvent,this.tabEvent.bindWithEvent(this,tab));
35
}, this);
36
},
37
38
tabEvent:function(e,tab)
{
39
e.preventDefault();
40
var index = this.tabs.indexOf(tab);
41
this.toggleSection(index);
42
},
43
44
toggleSection:function(index)
{
45
if(this.current === index) return;
46
this.hideSection(this.current);
47
this.current = index;
48
this.showSection(this.current);
49
},
50
51
showSection:function(index)
{
52
var tab = this.tabs[index];
53
var section = this.sections[index];
54
tab.addClass(this.options.selectedTabCss);
55
section.addClass(this.options.selectedSectionCss).show();
56
},
57
58
hideSection:function(index)
{
59
if (index===false) return;
60
var tab = this.tabs[index];
61
var section = this.sections[index];
62
tab.removeClass(this.options.selectedTabCss);
63
section.removeClass(this.options.selectedSectionCss).hide();
64
}
65
});
这样,我们就完成一个实现了最基本功能的选项卡: 最终示例