[Javascript][Mootools]用渐进增强的方式开发选项卡(Tabs)(三)

本文介绍了一个Tabs类的扩展实现,新增了动态添加和删除选项卡的功能。通过具体代码示例展示了如何利用自定义事件增强功能,并保持原有类的不变。
在这一节里,我将继续对Tabs类进行扩展,加上动态添加和删除选项卡的功能。

这个功能是我在看到126邮箱里用选项卡来查看邮件后,想到在Tabs类也实现相应的功能

思路如下:
添加新选项卡函数有四个参数,分别是新加标签的文本,新加内容的文本,新加选项卡的位置以及在选项标签上加入删除的按钮。

用传入的参数分别建立Element片段,加入到选项卡标签数组及选项卡内容数组,并将Element片段插入到DOM中,同时将选项卡标签事件绑定到新加标签,最后显示新加的内容。

而删除函数则是添加新选项卡函数的反过程。

我还在这两个函数里分别发布了两个自定义事件onAdd和onRemove,能更方便的实现自定义函数。

示例页

最终代码是在上节完成的代码后面,再使用implement方法在不改动原有类的情况下加上了新加了两个方法。

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 /**
 2  * implement two methods to Tabs class: addSection & removeSection
 3  */
 4 Tabs.implement({
 5     addSection:function(newTabHtml,newSectionHtml,pos,delA){
 6         var length = this.sectionsLength;
 7         pos = $pick(pos, length).limit(0, length);
 8         
 9         pos2 = pos==length?pos-1:pos;
10         var oldTab = this.tabs[pos2];
11         var oldSection = this.sections[pos2];
12 
13         var posMethod = pos == length ? 'after':'before';
14         var newTab = oldTab.clone().set('html',newTabHtml).inject(oldTab,posMethod);
15         var newSection = oldSection.clone().set('html',newSectionHtml).setStyle('display','none').inject(oldSection,posMethod);
16 
17         this.tabs.splice(pos,0,newTab)
18         this.sections.splice(pos,0,newSection)
19         this.sectionsLength++;
20 
21         if(pos<=this.current){
22             this.current++;
23         }
24         
25         var delA= newTab.getElement('a.'+delA);
26         if (delA){
27             delA.addEvent('click',this.removeSection.bindWithEvent(this,[newTab,delA]));
28         }
29         
30         newTab.addEvent(this.options.mouseEvent,this.tabEvent.bindWithEvent(this,newTab));
31         this.toggleSection(pos);
32         
33         this.fireEvent('onAdd',[newTab,newSection]);
34     },
35 
36     removeSection:function(e,tab,delA){
37         e.stop();
38         delA.removeEvents();
39         var index = this.tabs.indexOf(tab);
40 
41         this.tabs.splice(index,1);
42         var section = this.sections.splice(index,1)[0];
43         this.sectionsLength--;
44 
45         tab.removeEvents();
46         tab.destroy();
47         section.destroy();
48         
49         if(this.current==index){
50             this.current = (index-1).limit(0,this.sectionsLength);
51             this.showSection(this.current);
52         }
53         this.current--;
54         this.current = this.current.limit(0,this.sectionsLength);
55         this.fireEvent('onRemove',index);
56     }
57 });

转载于:https://www.cnblogs.com/noidea/archive/2009/01/03/1367703.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值