</pre><pre name="code" class="html"><!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>js基礎——圖片切換實例</title>
<style>
ul { padding:0; margin:0; }
li { list-style:none; }
body { background:#fff; }
#pic { width:400px; height:500px; position:relative; margin:0 auto; background:url(images/loader_ico.gif) no-repeat center #fff; }
#pic img { width:400px; height:500px; }
#pic ul { width:40px; position:absolute; top:0; right:-50px; }
#pic li { width:40px; height:40px; margin-bottom:4px; background:#666; cursor:pointer; }
#pic .active { background:#FC3; }
#pic span { top:0; }
#pic p { bottom:0; margin:0; }
#pic p,#pic span { position:absolute; left:0; width:400px; height:30px; line-height:30px; text-align:center; color:#fff; background:#000; }
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('pic');
var oImg = oDiv.getElementsByTagName('img')[0];
var oSpan = oDiv.getElementsByTagName('span')[0];
var oP = oDiv.getElementsByTagName('p')[0];
var oUl = oDiv.getElementsByTagName('ul')[0];
var aLi = oUl.getElementsByTagName('li');
var arrUrl = ['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg'];
var arrText = ['圖片一','圖片二','圖片三','圖片四'];
var num = 0;
//遍歷生成所有li
for(var i =0; i<arrUrl.length; i++){
oUl.innerHTML += '<li></li>';
}
//初始化函數
function init(){
oImg.src = arrUrl[num];
oSpan.innerHTML = 1+num + '/' + arrUrl.length;
oP.innerHTML = arrText[num];
for(var i=0; i<aLi.length; i++){
aLi[i].className = '';
}
aLi[num].className = 'active';
};
init();
//點擊按鈕切換圖片
for(var i=0; i<aLi.length; i++){
aLi[i].index = i;
aLi[i].onclick = function(){
num = this.index;
init();
};
}
};
</script>
</head>
<body>
<div id="pic">
<img src="" />
<span>數量正在加載中……</span>
<p>文字說明正在加載中……</p>
<ul></ul>
</div>
</body>
</html>
思路:
第一步:.獲取相關元素
第二步:通過for循環遍歷生成所有的li元素(按鈕)
第三步:函數初始化(按鈕狀態:清空全部,當前添加,方法2:清空上個,當前添加)
第四步:點擊按鈕切換圖片(自定義屬性的運用)