js实现选项卡切换

时间:2022-12-26 16:38:22

js实现选项卡切换

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>选项卡切换</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}

body{
font-size: 14px;
font-family: "微软雅黑";
color: #666;
margin: 30px;
}


ul{
width: 328px;
overflow: hidden;
background: #ccc;
}


li{
list-style: none;
float: left;
width: 80px;
height: 30px;
line-height: 30px;
text-align: center;
border: 1px solid transparent;
border-bottom: none;
cursor: pointer;
}


li.active{
border: 1px solid #000;
border-bottom: none;
height: 30px;
background: #ff0;
}


.contents{
width: 306px;
border: 1px solid #ccc;
border-top: none;
height: 160px;
line-height: 30px;
padding-left: 20px;
}


.contents div{display: none;}
</style>
</head>
<body>
<ul>
<li class="active">选择1</li>
<li>选择2</li>
<li>选择3</li>
<li>选择4</li>
</ul>
<div class="contents">
<div style="display: block;">内容1</div>
<div>内容2</div>
<div>内容3</div>
<div>内容4</div>
</div>
</body>
<script type="text/javascript">
window.onload=function(){
//获取每个li
var aLi = document.querySelectorAll('ul li');
//获取每个div
var aDiv = document.querySelectorAll('.contents div');
// 为每个li元素添加鼠标经过的事件
for(var i=0;i<aLi.length;i++){
aLi[i].index = i;
aLi[i].onmouseover = function(){
//鼠标经过时将每个li元素的样式设为空,div元素display为none
for(var j=0;j<aLi.length;j++){
aLi[j].className="";
aDiv[j].style.display="none";
}
//当前li元素样式设为active,div元素display为block,每次鼠标进过都会执行这个脚本
this.className ="active";
aDiv[this.index].style.display = "block";
}
}
}
</script>
</html>