用JS事件简易淘宝选项卡
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>淘宝简易选项卡</title>
<style>
*{margin: 0px; padding: 0px;}
li{list-style: none;}
#main{
width: 500px;
height: 350px;
margin: 100px auto;
}
#main #menu li{
float: left;
width: 25%;
line-height: 35px;
border-right: 1px solid #808080;
box-sizing: border-box;
text-align: center;
}
#main #menu li.action{
border: 1px solid orangered;
border-bottom: none;
}
#main #menu li:hover{
cursor: pointer;
}
#main #conter{
width:500px;
height: 315px;
clear: both;
background-color: skyblue;
border-top: #808080;
}
#main #conter div{
display: none;
line-height: 315px;
text-align: center;
}
#main #conter .ac{
display: block;
}
</style>
</head>
<body>
<div id="main">
<ul id="menu">
<li class="action">充话费</li>
<li>旅行</li>
<li>车险</li>
<li>游戏</li>
</ul>
<div id="conter">
<div class="ac">话费99折</div>
<div>国内七日游</div>
<div>车险98折</div>
<div>一刀就满级</div>
</div>
</div>
<script>
//获取元素节点
var Ali=document.getElementById('menu').getElementsByTagName('li');
var ds=document.getElementById('conter').getElementsByTagName('div');
//保存索引号
var index=0;
for(var i=0;i<Ali.length;i++){
Ali[i]._index=i;//给对象添加一个属性 保存索引号用
// li 点击事件
Ali[i].onclick=function(){
Ali[index].className="";//清除之前的样式
ds[index].className="";//清除内容区域的样式
this.className='action';//改变当前的样式
ds[this._index].className='ac';//改变当前的样式
index=this._index;//当前的索引号 把索引号赋值给index
};
}
</script>
</body>
</html>
开始的时候选项卡默认有样式。默认class有值
点击的时候,(去掉之前对象的class值 ,给当前对象的添加值)改变的当前的样式。 同时把之前的样式去掉。
遍历的时候 把索引保存到 对象新建的属性中。 方便使用,避免闭包问题。
重要的是保存索引,和获取当前的索引。