JS图片切换案例
一、案例需求
点击上一张或下一张按钮,图片会切换
二、案例分析、
1、事件源:按钮(button)
2、事件类型:点击(onclick)
3、事件处理程序:
(1)首先要判断图片编号
(2)图片切换:改变img的src路径
三、准备工作
1、照片4张
2、命名格式统一:p1.png、p2.png、p3.png、p4.png
3、将4张照片放入image文件里
四、代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片切换</title>
<style>
img {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<img src="images/image01.jpg" id="flower">
<br>
<button id="prev">上一张</button>
<button id="next">下一张</button>
<script>
// 1. 获取元素
var img = document.querySelector('img')
var btn1 = document.querySelector('#prev')
var btn2 = document.querySelector('#next')
var minIndex = 1,
maxIndex = 4,
currentIndex = minIndex;
// 2. 添加事件
btn1.onclick = function() {
//判断编号是否大于4,大于则将最小值赋给当前索引
if (currentIndex === minIndex) {
currentIndex = maxIndex;
} else {
currentIndex--;
}
img.src = 'images/image0' + currentIndex + '.jpg';
// img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6语法
};
btn2.onclick = function() {
//判断编号是否大于4,大于则将最小值赋给当前索引
if (currentIndex >= maxIndex) {
currentIndex = minIndex;
} else {
currentIndex++;
}
img.src = 'images/image0' + currentIndex + '.jpg';
// img.setAttribute('src', `images/image0${currentIndex}.jpg`); //ES6语法
};
</script>
</body>
</html>