纯js实现网页tab选项卡切换效果
1、新建html文档。
2、书写html。
<div id="tab">
<div class="tabList">
<ul>
<li class="cur">百度经验</li>
<li>百度经验</li>
<li>百度经验</li>
<li>百度经验</li>
</ul>
</div>
<div class="tabCon">
<div class="cur">百度经验</div>
<div>百度经验</div>
<div>百度经验</div>
<div>百度经验</div>
<div>百度经验</div>
</div>
</div>
3、书写css样式。
<style>
* { margin: 0; padding: 0; }
body { font-size: 14px; font-family: "Microsoft YaHei"; }
ul, li { list-style: none; }
#tab { position: relative; }
#tab .tabList ul li { float: left; background: #fefefe; background: -moz-linear-gradient(top, #fefefe, #ededed); background: -o-linear-gradient(left top, left bottom, from(#fefefe), to(#ededed)); background: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#ededed)); border: 1px solid #ccc; padding: 5px 0; width:200px; text-align: center; margin-left: -1px; position: relative; cursor: pointer; }
#tab .tabCon { position: absolute; left: -1px; top: 32px; border: 1px solid #ccc; border-top: none; width: 803px; height: 100px; }
#tab .tabCon div { padding: 10px; position: absolute; opacity: 0; filter: alpha(opacity=0); }
#tab .tabList li.cur { border-bottom: none; background: #fff; }
#tab .tabCon div.cur { opacity: 1; filter: alpha(opacity=100); }
</style>
4、书写js。
<script>
window.onload = function() {
var oDiv = document.getElementById("tab");
var oLi = oDiv.getElementsByTagName("div")[0].getElementsByTagName("li");
var aCon = oDiv.getElementsByTagName("div")[1].getElementsByTagName("div");
var timer = null;
for (var i = 0; i < oLi.length; i++) {
oLi[i].index = i;
oLi[i].onmouseover = function() {
show(this.index);
}
}
function show(a) {
index = a;
var alpha = 0;
for (var j = 0; j < oLi.length; j++) {
oLi[j].className = "";
aCon[j].className = "";
aCon[j].style.opacity = 0;
aCon[j].style.filter = "alpha(opacity=0)";
}
oLi[index].className = "cur";
clearInterval(timer);
timer = setInterval(function() {
alpha += 2;
alpha > 100 && (alpha = 100);
aCon[index].style.opacity = alpha / 100;
aCon[index].style.filter = "alpha(opacity=" + alpha + ")";
alpha == 100 && clearInterval(timer);
},
5)
}
}
</script>
5、查看效果。