原生javascript实现Tab选项卡切换功能
内容摘要
分析个人用原生JS获取类名元素的代码:
\\s|$)");
for(var n=0,i=node.length;n<i;n++){
if(p.test(node[n].className)){
\\s|$)");
for(var n=0,i=node.length;n<i;n++){
if(p.test(node[n].className)){
文章正文
分析个人用原生JS获取类名元素的代码:
\\s|$)");
for(var n=0,i=node.length;n<i;n++){
if(p.test(node[n].className)){
elem.push(node[n]);
}
}
return elem;
}
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元素,排除空白符.
移除元素的类名:
\\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);
if(!p || c.length==0) return null;
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';
}
}
}
}
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);
if(!p || c.length==0) return null;
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';
}
}
}
}
最终效果图展示:
效果是不是很棒呢,而且兼容性也不错,代码也很简洁,完全可以替代庞大的jQuery选项卡切换插件了。
代码注释