*{
margin: 0;
padding: 0 ;
}
.imgDiv , img{
width: 400px;
height: 400px;
border: 1px solid blue;
}
.imgDiv{
/* 父级元素 相对定位 */
position: relative;
}
img{
/* 绝对定位 */
position: absolute;
}
.wai{
position: relative;
width: 400px;
height: 400px;
border: 1px solid red;
margin: auto;
}
#btn1 {
position: absolute;
top: 40%;
font-size: 50px;
color: azure;
text-decoration: none;
}
#btn2 {
position: absolute;
top: 40%;
left: 90%;
font-size: 50px;
color: azure;
text-decoration: none;
}
span{
width: 20px;
height: 20px;
border: 2px solid white;
margin: 10px;
border-radius: 50%;
display: block;
float: left;
}
.xia{
position: absolute;
top: 90%;
left: 20%;
}
.active{
background-color: red;
}
var interval ; // 定时器的名字
var index = 0 ; // 图片元素的下标
// 图片的个数
var imgLength = document.getElementsByTagName("img").length;
// 切换下一张图片
function nextImg(){
index++ ;
addStyle();
}
// 切换上一张图片
function prevImg(){
index-- ;
addStyle();
}
// 给当前元素设置样式
function addStyle(){
$("img").eq(index % imgLength).fadeIn(); // 当前图片 淡入
$("img").eq(index % imgLength).siblings().fadeOut();// 其他兄弟元素 淡出
$("span").eq(index % imgLength).addClass("active");
$("span").eq(index % imgLength).siblings().removeClass("active");
}
// 鼠标移入 的时候 暂停切换
$(".wai").mouseover( function(){
clearInterval(interval); // 停止定时器
});
// 移出是 继续轮播
$(".wai").mouseout( function(){
action();
});
// 切换上一张图片
$("#btn1").click(function(){
prevImg();
});
// 切换下一张图片
$("#btn2").click(function(){
nextImg();
});
// 定义周期性函数
function action(){
interval = setInterval(function(){
nextImg();
} , 1000);
}
action();
<!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>
<link rel="stylesheet" href="css/imageRotation.css">
</head>
<body>
<div class="wai">
<div class="imgDiv">
<img src="image/1.jpg" alt="">
<img src="image/2.jpeg" alt="">
<img src="image/3.jpg" alt="">
<img src="image/4.jpg" alt="">
<img src="image/5.jpg" alt="">
</div>
<div>
<a id="btn1" href="#"> < </a>
<a id="btn2" href="#"> > </a>
</div>
<div class="xia">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</body>
<script src="../js/jquery-3.6.3.min.js"></script>
<script src="js/imgRotation.js"></script>
</html>