方法一是比较笨一点的方法,二需要借助遍历来操作。知识点this :表示当前
方法一:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#tab{
position:relative;
}
#tab div{
border:1px solid #eee;width:250px;
height:50px;
position:absolute;
display: none;
}
</style>
<script>
window.onload=function(){
var tab=document.getElementById("tab");
var div1=tab.getElementsByTagName("div")[0];
var div2=tab.getElementsByTagName("div")[1];
var div3=tab.getElementsByTagName("div")[2];
var but1=document.getElementsByTagName("button")[0];
var but2=document.getElementsByTagName("button")[1];
var but3=document.getElementsByTagName("button")[2];
but1.onclick=function(){
div1.style.display="block";
var str="123456789abcdef";
var bg="#";
div2.style.display="none";
div3.style.display="none";
but1.style.backgroundColor="red";
but2.style.backgroundColor="";
but3.style.backgroundColor="";
}
but2.onclick=function(){
div2.style.display="block";
div1.style.display="none";
div3.style.display="none";
but2.style.backgroundColor="red";
but1.style.backgroundColor="";
but3.style.backgroundColor="";
}
but3.onclick=function(){
div3.style.display="block";
div2.style.display="none";
div1.style.display="none";
but3.style.backgroundColor="red";
but2.style.backgroundColor="";
but1.style.backgroundColor="";
}
}
</script>
</head>
<body>
<button>table1</button><button>table2</button><button>table3</button>
<div id="tab">
<div>tab1</div>
<div>tab2</div>
<div>tab3</div>
</div>
</div>
</body>
</html>
方法二:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div span {
width: 50px;
border: 1px solid #eee;
display: inline-block;
height: 30px;
line-height: 30px;
background-color: #f5f5f5;
}
#tab .con{
border: 1px solid #eee;
width: 150px;
height: 200px;
display:none;
position:absolute;
}
#tab .con:first-of-type{
display:block;
}
.act {
background-color: orange;
}
</style>
<script>
window.onload = function() {
//获取元素
var tab = document.getElementById("tab");
var spans = tab.getElementsByTagName("span");
var cons = tab.getElementsByClassName("con");
//遍历
for(var i = 0; i < spans.length; i++) {
spans[i].idx = i;
spans[i].onclick=function(){
for(var i=0;i<spans.length;i++){
spans[i].className =" ";
cons[i].style.display="none";
}
this.className="act";
cons[this.idx].style.display="block"
}
}
}
</script>
</head>
<body>
<div id="tab">
<span class="act">tab1</span>
<span >tab2</span>
<span >tab3</span>
<div class="con" >table1</div>
<div class="con">table2</div>
<div class="con">table3</div>
</div>
</body>
</html>