直接上代碼
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>相冊</title>
<script type = "text/javascript">
//記錄<img>對象的數組
var images = [];
//初始化事件處理函數
function initdsy () {
//所有的<img>元素
alert('44');
var imgArr= document.getElementsByTagName("img");
for(var i=0;i<imgArr.length;i++){
//找到所有class=img的<img>元素
if(imgArr[i].className=="img"){
//保存在imgages數組中
images.push(imgArr[i]);
//添加mouseover事件處理函數
addEventListener(imgArr[i],"mouseover",handleEvent);
}
}
}
//添加事件處理函數
function addEventListener(ele,type,func){
//DOM兼容瀏覽器
if(ele.addEventListener){
ele.addEventListener(type,func,false);
}else {//IE
ele.attachEvent("on" + type,func);
}
}
// 在mouseover事件的處理函數handleEvent中找到圖片位置,顯示該圖片。
function handleEvent(evt) {
//事件對象
var event = window.event ? window.event : evt;
//事件源:預覽圖對象
var target =event.target ? event.target : event.srcElement;
//找到當前圖片的位置
for(var i = 0;i <images.length;i++){
if(images[i] ==target) break;
}
//200ms延時之後顯示該圖片
setTimeout(function (){
go(i);
}, 200);
}
function go(i) {
$("showpic").src=images[i].src;
$("show").style.display = "";
var next =(i+1)%images.length;
// alert(i+'ss');
var prev=(i-1+images.length)%images.length;
// alert(prev+'prev');
// alert(next+'next');
$("prev").onclick = function(){
setTimeout(function (){
// alert("111");
go(prev);
},200);
};
//設置"下一張"按鈕的事件處理函數
$("next").onclick = function(){
//200ms之後切換到下一張圖片
setTimeout(function () {
//alert("111");
go(next);
},200);
};
}
function $(id){
return document.getElementById(id);
}
//隱藏大圖顯示區域
function hide() {
$("show").style.display="none";
}
</script>
<style type="text/css">
* {
Font-family:Tahoma;
Font-size:12pt;
Text-align:center;
Margin:0 auto;
}
Body{
Margin:10px;
}
.img{
Height:80px;
Cursor:pointer;
margin:0;
}
#gallary{
float:left;
height:80px;
Text-align:center;
}
.bdr {
border-top:4px dashed;
border-bottom:4px dashed;
clear:both;
}
#show {
position:absolute;
top:200px;
left:250px;
backgrond-color:#313131;
padding:10px 10px 10px 10px;
}
#showpic{
cursor:pointer;
margin-bottom:5px;
}
#prev,#next {
cursor:pointer;
color:#111111;
font-weight:bold;
}
</style>
</head>
<body οnlοad="initdsy()">
<div class="bdr">
</div>
<div id="gallay">
<img class="img" src="pic1.jpg" alt="pic1">
<img class="img" src="pic2.jpg" alt="pic2">
<img class="img" src="pic3.jpg" alt="pic3">
<img class="img" src="pic4.jpg" alt="pic4">
<img class="img" src="pic5.jpg" alt="pic5">
</div>
<div class="bdr">
</div>
<div id="show" style="display:none">
<img id="showpic"src="" alt="" οnclick="hide()" />
<div>
<span id="prev">上一張</span>
<span id="next">下一張</span>
</div>
</div>
</body>
</html>
go(i)的作用是切換到第i張圖片,該函數還負責設置"上一張"。"下一張"按鈕的click事件處理函數