HTML
<body>
<div class="wai">
<div class="imgDiv">
<img src="images/0.jpg" alt="" >
<img src="images/1.jpg" alt="">
<img src="images/2.jpg" alt="">
<img src="images/3.jpg" alt="">
<img src="images/4.jpg" alt="">
</div>
<div>
<a id="a1" href="#"> < </a>
<a id="a2" href="#"> > </a>
</div>
<div class="xia">
<span id="s1" ></span>
<span id="s2"></span>
<span id="s3"></span>
<span id="s4"></span>
<span id="s5" class="active"></span>
</div>
</div>
</body>
<script src="js/jquery-3.6.3.min.js"></script>
<script src="js/q1.js"></script>
CSS
*{
margin: 0;
padding: 0 ;
}
.imgDiv , img{
width: 600px;
height: 500px;
border: 1px solid blue;
}
.imgDiv{
/* 父级元素 相对定位 */
position: relative;
}
img{
/* 绝对定位 */
position: absolute;
}
.wai{
position: relative;
width: 600px;
height: 500px;
margin: auto;
}
#a1 {
position: absolute;
top: 40%;
font-size: 50px;
color: rgb(255, 95, 3);
text-decoration: none;
}
#a2 {
position: absolute;
top: 40%;
left: 95%;
font-size: 50px;
color: rgb(255, 17, 0);
text-decoration: none; /* 去掉下划线*/
}
span{
width: 20px;
height: 20px;
border: 2px solid rgb(255, 187, 0);
margin: 10px;
border-radius: 50%;
display: block; /* 块状*/
float: left;
}
span:hover,span:active{
box-shadow: 1px 1px 1px 1px rgb(87, 81, 0);
width: 22px;
height: 22px;
}
.xia{
position: absolute;
top: 90%;
left: 30%;
}
.active{
background-color: red;
}
JS
var interval ; // 定时器的名字
var index = -1 ; // 图片元素的下标
// 图片的个数
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");
}
// 点击切换
$("#s1").click(function(){
index = 0;
addStyle();
})
$("#s2").click(function(){
index = 1;
addStyle();
})
$("#s3").click(function(){
index = 2;
addStyle();
})
$("#s4").click(function(){
index = 3;
addStyle();
})
$("#s5").click(function(){
index = 4;
addStyle();
})
// 鼠标移入 的时候 暂停切换
$(".wai").mouseover( function(){
clearInterval(interval); // 停止定时器
});
// 移出是 继续轮播
$(".wai").mouseout( function(){
action();
});
// 切换上一张图片
$("#a1").click(function(){
prevImg();
});
// 切换下一张图片
$("#a2").click(function(){
nextImg();
});
// 定义周期性函数
function action(){
interval = setInterval(function(){
nextImg();
} , 1000);
}
action();
效果图