使用JavaScript中的數組來實現點擊按鈕圖片切換
<!DOCTYPE html>
<html>
<head>
<title>圖片瀏覽器</title>
<meta charset="utf-8">
<script type="text/javascript">
var imgName = Array("pic1.jpg","pic2.jpg","pic3.jpg","pic4.jpg","pic5.jpg");
var foot = 0 ; //創建數組角標
window.onload = function(){
var pButton = document.getElementById("previousButton"); //定義上一頁按鈕
var nButton = document.getElementById("nextButton"); //定義下一頁按鈕
var img = document.getElementById("img"); //定義圖片
nButton.addEventListener("click",function(){ //為上一張按鈕添加監聽事件
foot++; //點擊一下foot加一
if( foot > imgName.length - 1){
foot = 0 ;
}
img.src = "img/" + imgName[foot];
},false);
pButton.addEventListener("click",function(){ //為上一張按鈕添加監聽事件
foot -- ; //點擊一下foot減一
if( foot < 0){
foot = imgName.length - 1 ;
}
img.src = "img/" + imgName[foot];
},false);
}
</script>
</head>
<body>
<span id="info">
<img id="img" src="img/pic1.jpg" width="20%">
</span>
<div>
<button id="previousButton">上一張</button>
<button id="nextButton">下一張</button>
</div>
</body>
</html>
實現結果
點擊下一張