<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin:0px;
padding:0px;
}
#box1{
width:360px;
background-color: #5F9EA0;
overflow: hidden;
}
#ig{
width:360px;
height:300px;
}
#box1 button{
float: left;
}
#box1 #but01{
margin-left:130.5px;
margin-right:10px;
}
#box1 h1{
text-align: center;
font-family:"微軟雅黑";
font-size:30px;
}
</style>
<script>
window.onload=function(){
var but01=document.getElementById("but01");
var but02=document.getElementById("but02");
var box=document.getElementById("box1");
var h1=document.getElementsByTagName("h1")[0];
var ig=document.getElementById("ig");
//存放圖檔
var imgArr=["img/0.jpg","img/1.jpg","img/2.jpg",
"img/3.jpg","img/4.jpg","img/5.jpg",
"img/6.jpg","img/7.jpg","img/8.jpg",
"img/9.jpg"];
var index=0;
but01.onclick=function(){
index--;
//檢測index的大小,如果小于0,就換成最後一張
if(index<0){
index=imgArr.length-1;
}else{
//檢測index有沒有越界(是否大于數組長度)
index%=imgArr.length;
}
//改變上面的h1,索引從0開始,圖檔從1開始,是以+1
h1.innerHTML="第"+(index+1)+"張";
//改變圖源
ig.src=imgArr[index];
};
but02.onclick=function(){
index++;
//檢測index的大小,如果超出了就循環
index%=imgArr.length;
//切換的時候改變内容
h1.innerHTML="第"+(index+1)+"張";
//改變圖源
ig.src=imgArr[index];
};
};
</script>
</head>
<body>
<div id="box1">
<h1>第1張</h1>
<img id="ig" src="img/0.jpg">
<button id="but01">上一張</button>
<button id="but02">下一張</button>
</div>
</body>
</html>