tab切换 原生js

时间:2022-04-06 11:15:54
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin:0; padding:0;}
.out-box{overflow:hidden;}
ul{overflow:hidden;}
ul li{list-style: none; float:left; margin-right:10px;}
.con{width:300px;height:150px; line-height:150px; display: none; background:red; position: absolute; top:30px; left:0;}
.con1{background:red;}
.con2{background:blue;}
.con3{background:yellow;} </style>
</head>
<body> <div class="out-box" id="box">
<ul id="ul">
<li><button>按钮1</button></li>
<li><button>按钮2</button></li>
<li><button>按钮3</button></li>
</ul>
<div class="con con1">1111111111</div>
<div class="con con2">1111111111</div>
<div class="con con3">1111111111</div> </div> <script>
/*方法一*/
var aUl=document.getElementById("ul");
var aLi=aUl.getElementsByTagName("li");
var aDiv=document.getElementsByClassName("con");
console.log(aDiv);
for(var i=0; i<aLi.length; i++){
aLi[i].index=i; //把i值存起来
aLi[i].onclick= function () {
for(var j=0; j<aDiv.length; j++){
aDiv[j].style.display="none"; //清除div样式
}
aDiv[this.index].style.display="block"; //给当前的div盒子赋样式 }
} /*方法二*/
var aUl=document.getElementById("ul");
var aLi=aUl.getElementsByTagName("li");
var aDiv=document.getElementsByClassName("con");
for(var i=0; i<aLi.length; i++){
(function(i){ //自执行函数会直接把i值保存起来
aLi[i].onclick= function () {
for(var j=0; j<aDiv.length; j++){
aDiv[j].style.display="none"; //清除div样式
                }
aDiv[i].style.display="block"; //给当前的div盒子赋样式

            }
})(i); } </script> </body>
</html>