JavaScript实现图片切换(数组版)
使用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>
实现结果

点击下一张


浙公网安备 33010602011771号