<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0px; padding: 0px; } #outer{ width: 240px; mar ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
}
#outer{
width: 240px;
margin: 50px auto;
background-color: greenyellow;
padding: 10px;
text-align: center;
}
img{
width: 240px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var img=document.getElementsByTagName("img")[0];
var imgArr=["img/cat.jpg","img/flower.jpg","img/san.jpg"];
var n=0;
var info=document.getElementById("info");
info.innerHTML="一共"+imgArr.length+"張,這是第"+(n+1)+"張!"
//獲取兩個按鈕
var prev=document.getElementById("prev");
var next=document.getElementById("next");
//為兩個按鈕綁定事件
prev.onclick=function(){
n--;
if (n<0) {n=imgArr.length-1;}
img.src=imgArr[n];
info.innerHTML="一共"+imgArr.length+"張,這是第"+(n+1)+"張!"
};
next.onclick=function(){
n++;
if (n>imgArr.length-1) {n=0;}
img.src=imgArr[n];
info.innerHTML="一共"+imgArr.length+"張,這是第"+(n+1)+"張!"
};
}
</script>
</head>
<body>
<div id="outer">
<p id="info">一共3張,這是第一張!</p>
<img src="img/cat.jpg" alt="貓">
<button id="prev">上一張</button>
<button id="next">下一張</button>
</div>
</body>
</html>