方法三:显示和隐藏通过是有拥有class控制,先把所有的内容隐藏dispaly设为none,而该class的display设置为block,遍历所有标题节点和内容节点,点击标题后,该标题节点和对用的内容节点拥有class,其他的没有。
<
html
>
<
head
>
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=utf-8"
/>
<
style
>
*{
padding: 0;
margin: 0;
}
li{
list-style: none;
float:left;
}
#tabCon {
clear: both;
}
#tabCon div {
display:none;
}
#tabCon div.fdiv {
display:block;
}
</
style
>
</
head
>
<
body
>
<
div
id
=
"tanContainer"
>
<
div
id
=
"tab"
>
<
ul
>
<
li
class
=
"fli"
>标题一</
li
>
<
li
>标题二</
li
>
<
li
>标题三</
li
>
<
li
>标题四</
li
>
</
ul
>
</
div
>
<
div
id
=
"tabCon"
>
<
div
class
=
"fdiv"
>内容一</
div
>
<
div
>内容二</
div
>
<
div
>内容三</
div
>
<
div
>内容四</
div
>
</
div
>
</
div
>
</
body
>
<
script
>
var tabs=document.getElementById("tab").getElementsByTagName("li");
var divs=document.getElementById("tabCon").getElementsByTagName("div");
for(var i=0;i<
tabs.length
;i++){
tabs[i]
.onclick
=
function
(){change(this);}
}
function change(obj){
for(var
i
=
0
;i<tabs.length;i++){
if(tabs[i]==obj){
tabs[i]
.className
=
"fli"
;
divs[i]
.className
=
"fdiv"
;
}else{
tabs[i]
.className
=
""
;
divs[i]
.className
=
""
;
}
}
}
</script>
</
html
>
该方法的缺点是,内容块的div下面不能再有div标签了。
方法四:不用js,用“input:checked”来做tab切换,先把所有的内容隐藏,被选中的内容显示。<
html
>
<
head
>
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=utf-8"
/>
<
title
>input:checked实现tab切换</
title
>
<
style
>
input{
opacity: 0;/*隐藏input的选择框*/
}
label{
cursor: pointer;/*鼠标移上去变成手状*/
float: left;
}
label:hover{
background: #eee;
}
input:checked+label{
color: red;
}
/*选择前面有.tabs input:nth-of-type(x):checked的.panels .panel:nth-child(x)*/
.tabs input:nth-of-type(1):checked~.panels .panel:nth-child(1),
.tabs input:nth-of-type(2):checked~.panels .panel:nth-child(2){
opacity: 1;
}
.panel{
opacity: 0;
position: absolute;/*使内容区域位置一样*/
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"tabs"
>
<
input
checked
id
=
"one"
name
=
"tabs"
type
=
"radio"
>
<
label
for
=
"one"
>标题一</
label
>
<
input
id
=
"two"
name
=
"tabs"
type
=
"radio"
>
<
label
for
=
"two"
>标题二</
label
>
<
div
class
=
"panels"
>
<
div
class
=
"panel"
>
<
p
>内容一</
p
>
</
div
>
<
div
class
=
"panel"
>
<
p
>内容二</
p
>
</
div
>
</
div
>
</
div
>
</
body
>
</
html
>
该方法的缺点是,不同区域切换只能通过点击。