原生js实现点击“上一张”、“下一张”按钮切换图片
目录结构:代码:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device
·
目录结构:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>图片切换</title>
</head>
<body>
<div>
<img id="first" src="./images/img01.jpg" width="500px" height="300px" />
</div>
<button style="margin-left: 180px;" id="prev">上一张</button>
<button id="next">下一张</button>
<script>
// 1.获取DOM对象
var img = document.getElementById("first");
var prevBtn = document.getElementById("prev");
var nextBtn = document.getElementById("next");
// 2.添加点击事件
var minPage = 1;
var maxPage = 5;
var currentPage = minPage;
// 上一张按钮
prevBtn.onclick = function() {
// 第一张的上一张是最后一张
if(currentPage === minPage) {
currentPage = maxPage;
} else {
currentPage--;
}
img.setAttribute('src',`./images/img0${currentPage}.jpg`);
}
// 下一张按钮
nextBtn.onclick = function() {
// 最后一张的下一张是第一张
if(currentPage === maxPage) {
currentPage = minPage;
} else {
currentPage++;
}
img.setAttribute('src',`./images/img0${currentPage}.jpg`);
}
</script>
</body>
</html>
样式:
更多推荐
已为社区贡献18条内容
所有评论(0)