原生javascript-Tab选项卡-面向对象

王朝学院·作者佚名  2016-05-05
窄屏简体版  字體: |||超大  

在线实例:http://www.lgyweb.com/tab/

分析个人用原生JS获取类名元素的代码:

复制代码

getByClassName:function(className,parent){

var elem = [],

node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),

p = new RegExp("(^|\\s)"+className+"(\\s|$)");

for(var n=0,i=node.length;n<i;n++){

if(p.test(node[n].className)){

elem.push(node[n]);

}

}

return elem;

}

复制代码

parent参数是可选的,但需要先判断它是否存在,且是节点dom元素 parent != undefined&&parent.nodeType==1 ,nodeType == 1可以判断节点是否为dom元素,在火狐浏览器里面,空白也算是节点(.childnodes),用这个属性就判断是否为dom元素,排除空白符.

移除元素的类名:

var cur = new RegExp(this.sCur,'g'); //this.sCur就是类名,这里是用变量保存 如:this.sCur = "cur";

this.oTab_btn[n].className = this.oTab_btn[n].className.replace(cur,'');

以下为详细代码:

复制代码

function LGY_tab(option){

this.oTab_btn = this.getDom(option.tabBtn);//切换点击的元素

this.oTab_clist = this.getDom(option.tabCon); //切换的内容

this.sCur = option.cur; //激活的状态

this.type = option.type || 'click';

this.nLen = this.oTab_btn.length;

this.int();

}

LGY_tab.PRototype = {

getId:function(id){

return document.getElementById(id);

},

getByClassName:function(className,parent){

var elem = [],

node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),

p = new RegExp("(^|\\s)"+className+"(\\s|$)");

for(var n=0,i=node.length;n<i;n++){

if(p.test(node[n].className)){

elem.push(node[n]);

}

}

return elem;

},

getDom:function(s){

var nodeName = s.split(' '),

p = this.getId(nodeName[0].slice(1)),

c = this.getByClassName(nodeName[1].slice(1),p);

return c;

},

change:function(){

var cur = new RegExp(this.sCur,'g');

for(var n=0;n<this.nLen;n++){

this.oTab_clist[n].style.display = 'none';

this.oTab_btn[n].className = this.oTab_btn[n].className.replace(cur,'');

}

},

int:function(){

var that = this;

this.oTab_btn[0].className += ' '+this.sCur;

this.oTab_clist[0].style.display = 'block';

for(var n=0;n<this.nLen;n++){

this.oTab_btn[n].index = n;

this.oTab_btn[n]['on'+this.type] = function(){

that.change();

that.oTab_btn[this.index].className +=' ' + that.sCur;

that.oTab_clist[this.index].style.display = 'block';

}

}

}

}

复制代码

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航