tab切换的两种方法

时间:2023-03-09 19:59:19
tab切换的两种方法
方法一、主要使用了传递参数的思想,把循环变量不能使用转换了一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.nav{
width: 100%;
height: 50px;
text-align: center;
}
.nav li{
display: inline-block;
padding-left: 20px;
padding-right: 20px;
list-style: none;
background: red;
color: #fff;
text-align: center;
height: 50px;
width: 100px;
line-height: 50px;
border-radius: 10px;
}
.container{
width: 100%;
height: 400px;
background: #cccccc;
border-radius: 20px;
text-align: center;
line-height: 400px;
}
.container div{
position: absolute;
/*background: #fff;*/
width: 80%;
left: 10%;
top: 15%;
height: 300px;
margin: 0 auto;
border-radius: 20px;
/*display: none;*/
}
.show{
z-index: 99;
background: #cc6600;
color: #fff;
}
.hide{
/*display: none;*/
z-index: 0;
}
</style>
</head>
<body>
<div class="nav">
<ul>
<li>导航一</li>
<li>导航二</li>
<li>导航三</li>
<li>导航四</li>
<li>导航五</li>
</ul>
</div>
<div class="container" id='container'>
<div class='show'>内容一</div>
<div>内容二</div>
<div>内容三</div>
<div>内容四</div>
<div>内容五</div>
</div>
</body>
<script>
window.onload=function(){
// 1、获取触发事件的元素
var oli = document.getElementsByTagName('li');
for (var i = 0; i < oli.length; i++) {
// 2、给触发元素添加触发事件
oli[i].onmouseover=function(){
// 3、调用函数,执行事件
change(this);
}
}
function change(obj){
var oli = document.getElementsByTagName('li');
var container = document.getElementById('container');
var oDiv = container.getElementsByTagName('div');
for (var i= 0; i< oli.length; i++) {
if(oli[i]==obj){
oDiv[i].className='show';
}else{
oDiv[i].className ='hide';
}
}
}
}
方案二、排他思想和对象思想
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
width: 100%;
margin: 0 auto;
}
.body{
background: #cc6600;
width: 100%;
height: 500px;
}
.body div{
position: absolute;
background: #fff;
width: 50%;
height: 50%;
left: 25%;
top: 25%;
display: none;
}
.body div.show{
display: block;
}
</style>
</head>
<body>
<div class="container">
<button>导航一</button>
<button>导航二</button>
<button>导航三</button>
<button>导航四</button>
<button>导航五</button>
<button>导航六</button>
</div>
<div class="body" id='body'>
<div class='show'>内容一</div>
<div>内容二</div>
<div>内容三</div>
<div>内容四</div>
<div>内容五</div>
<div>内容六</div>
</div>
</body>
<script>
window.onload=function(){
// 1、获取元素
var btns = document.getElementsByTagName('button');
var body = document.getElementById('body');
var oDiv = body.getElementsByTagName('div');
// 2、遍历元素
for(var i = 0;i<btns.length;i++){
// 6、自定义属性,使触发元素与目标元素相关联
btns[i].index=i;
// 3、添加事件
btns[i].onclick=function(){
// 4、遍历清除样式
for (var i= 0; i< btns.length; i++) {
btns[i].className='';
oDiv[i].className='';
}
// 5、给目标元素设置样式
oDiv[this.index].className='show';
}
}
}
</script>
</html>