<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上下切换图片</title>
</head>
<body>
<img name = 'icon' src="images/IMG_2931.JPG">
<p></p>
<button>上一张</button>
<button>下一张</button>
<script>
//1.全局变量
var maxIndex = 2934;
var minIndex = 2931;
var currentIndex = minIndex;
//2. 拿到需要操作的标签
var img = document.getElementsByName('icon')[0];
var pre = document.getElementsByTagName('button')[0];
var next = document.getElementsByTagName('button')[1];
//3.监听按钮的点击
//3.1 上一张
pre.onclick = function () {
if (currentIndex == minIndex){
currentIndex = maxIndex;
} else{
currentIndex -= 1;
}
//改变图片
img.src = 'images/IMG_' + currentIndex + '.JPG';
}
//3.2 下一张
next.onclick = function () {
if (currentIndex == maxIndex){
currentIndex = minIndex;
} else{
currentIndex += 1;
}
//改变图片
img.src = 'images/IMG_' + currentIndex + '.JPG';
}
</script>
</body>
</html>
image.png
网友评论