js轮播图实现简单代码,显示区有左右按钮与5张图片
时间: 2024-05-02 11:19:19 浏览: 91
可以使用以下代码实现简单的js轮播图:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS轮播图</title>
</head>
<body>
<div id="container">
<img id="img1" src="img1.jpg" alt="图片1" />
<img id="img2" src="img2.jpg" alt="图片2" />
<img id="img3" src="img3.jpg" alt="图片3" />
<img id="img4" src="img4.jpg" alt="图片4" />
<img id="img5" src="img5.jpg" alt="图片5" />
<button id="prevBtn">上一张</button>
<button id="nextBtn">下一张</button>
</div>
<script type="text/javascript">
var curIndex = 0;
var imgDuration = 3000;
var imgNum = 5;
var timer = setInterval(changeImg,imgDuration);
document.getElementById("prevBtn").addEventListener("click",prevImg);
document.getElementById("nextBtn").addEventListener("click",nextImg);
function changeImg(){
var container = document.getElementById("container");
curIndex++;
if(curIndex == imgNum){
curIndex = 0;
}
container.style.transform = "translateX(-" + curIndex * 600 + "px)";
}
function prevImg(){
var container = document.getElementById("container");
curIndex--;
if(curIndex == -1){
curIndex = imgNum - 1;
}
container.style.transform = "translateX(-" + curIndex * 600 + "px)";
}
function nextImg(){
var container = document.getElementById("container");
curIndex++;
if(curIndex == imgNum){
curIndex = 0;
}
container.style.transform = "translateX(-" + curIndex * 600 + "px)";
}
</script>
</body>
</html>
```
其中,`imgDuration` 是每张图片显示的时间,`imgNum` 是图片的数量,`container.style.transform` 用来实现图片的移动效果。左右按钮的功能分别由 `prevImg` 和 `nextImg` 函数实现。
阅读全文