在平常的網頁中,選項卡是常見的一直展示方式。今天我將用JS實現圖層的切換。可能用到的方法比較笨重,如果你有更好的方法,期待着你與我的分享。
大致思想:實現圖層切換,需要通過JS控制圖層的CSS樣式屬性值,從而達到想要的效果。其中,最重要的屬性和值是:display=”block/none”;”block”代表着“顯示塊級”元素,而“none”,則表示“此元素不會被顯示”。
菜鳥代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TabControl01</title>
<meta name="author" content="Administrator" />
<!-- Date: 2014-06-18 -->
<style type="text/css">
.content{margin:0 auto;width:500px;height:450px;}
.content01{width:500px;height:50px;}
.content01 ul{margin:0;padding:0;overflow: hidden;}
.content01 li{width:100px;height:50px;list-style:none;text-align:center;line-height:50px;background-color:#A7C942;float:left;}
.content01 a:link{width:100px;height:50px;text-decoration:none;display:block;}
.content01 a:hover{width:100px;height:50px;background:#EAF2D3;}
.content02{width:500px;height:400px;background:#EAF2D3;}
.contentList{width:500px;height:400px;display:none;background:#EAF2D3;}
.contentList1{width:500px;height:400px;background:#EAF2D3;}
</style>
<script type="text/javascript">
function show(n){
var menu=document.getElementById("c").getElementsByTagName("li");
var showdiv=document.getElementById("d").getElementsByTagName("div");
for(var i=0;i<menu.length;i++){
menu[i].className=i==n?"now":"";
showdiv[i].style.display=i==n?"block":"none";
}
/*第26,27行的代碼,等價於:
if(i==n){
menu[i].className="now";
showdiv[i].style.display="block";
}else{
menu[i].className="";
showdiv[i].style.display="none";
}
* */
}
</script>
</head>
<body>
<div class="content">
<div id="c" class="content01">
<ul>
<li οnmοusemοve="show(0)" class="now"><a href="#">A</a></li>
<li οnmοusemοve="show(1)"><a href="#">B</a></li>
<li οnmοusemοve="show(2)"><a href="#">C</a></li>
<li οnmοusemοve="show(3)"><a href="#">D</a></li>
<li οnmοusemοve="show(4)"><a href="#">E</a></li>
</ul>
</div>
<div id="d" class="content02">
<div class="contentList1">1</div>
<div class="contentList">2</div>
<div class="contentList">3</div>
<div class="contentList">4</div>
<div class="contentList">5</div>
</div>
</div>
</body>
</html>