通过索引实现轮播图
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
* {
margin: 0;
padding: 0
}
#box {
width: 1200px;
height: 800px;
border: 5px solid purple;
margin: 0 auto;
}
#inner {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
top:0;left:0
}
#inner img {
width: 100%;
height: 100%;
}
button{font-size: 32px;font-weight: 600;z-index: 10;position:absolute;top:45%;left:0;}
button.left{left:0px}
button.right{left:1165px}
</style>
</head>
<body onload="rollback()">
<div id="box">
<div id="inner">
<img src="img/img1.jpeg" id="img_id" />
<button class="left"> < </button>
<button class="right"> > </button>
</div>
</div>
<script>
var timer;
// 全局i
var i = 1;
// 切换索引改变图片
function rollback() {
timer = setInterval(rollImg, 2000);
}
// 获取图片对象
var img_id = document.getElementById("img_id");
// 修改图片src方法
function rollImg() {
i++;
if (i == 6) {
i = 1;
}
img_id.src = "img/img" + i + ".jpeg"
console.log(i)
}
// 鼠标划入停止计时器
document.getElementById("box").addEventListener("mouseover",function () {
clearInterval(timer)
})
// 鼠标移出继续计时器
document.getElementById("box").onmouseout = function () {
rollback();
}
document.getElementsByClassName("left")[0].onclick=function(){
i--;
if(i<1){
i=5
}
img_id.src = "img/img" + i + ".jpeg"
}
document.getElementsByClassName("right")[0].onclick=function(){
i++;
if (i ==6) {
i = 1;
}
img_id.src = "img/img" + i + ".jpeg"
}
</script>
</body>
</html>
来源:CSDN
作者:冥冥自有定数
链接:https://blog.csdn.net/qq_44214801/article/details/103469172