实现效果:点击选项菜单更换对应内容
第一步 :首先进行简单布局
页面布局
<body>
<div class="container">
<ul class="items">
<li style="background: pink">第一项</li>
<li>第二项</li>
<li>第三项</li>
<li>第四项</li>
<li>第五项</li>
</ul>
<div class="box">第一项</div>
<div class="box">第二项</div>
<div class="box">第三项</div>
<div class="box">第四项</div>
<div class="box">第五项</div>
</div>
</body>
选项卡样式
<style>
*{
margin:0;
padding: 0;
list-style: none;
font-family: "微软雅黑";
font-size: 20px;
}
.container{
margin: 0 auto;
width: 500px;
height: 500px;
border: 1px solid black;
overflow: hidden;
}
.items li{
float: left;
width: 100px;
height: 40px;
text-align: center;
line-height: 40px;
border-bottom: 1px solid black;
}
.items li:hover{
color: red;
cursor: pointer;
background: hotpink;
}
.box{
margin: 0 auto;
width: 500px;
height: 460px;
line-height: 460px;
text-align: center;
}
</style>
第二步
获取元素
(要实现点击选项菜单更换对应内容的效果,所以我们在这里需要获取代表选项菜单的li元素,以及代表对应内容的box元素。)
var li=document.getElementsByTagName("li");
var box=document.getElementsByClassName("box");
第三步
利用for循环实现效果
for(var i=0; i<li.length; i++){
li[i].index=i; //储存下标
li[i].function(){ //给每一个选项卡添加点击事件
for(var j=0; j<box.length; j++){
li[j].style.background="#fff"; //循环清除选项卡样式,将选项卡菜单背景颜色设为白色
box[j].style.display="none"; // 循环隐藏对应内容样式
}
this.style.background="pink"; //循环添加选项卡样式,给选项卡菜单添加颜色,this代表的是此时点击的对象
box[this.index].style.display="block"; //当点击每一个选项卡时,循环显示对应内容样式
}
完成。