一、效果展示
二、完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
height: 300px;
width: 600px;
overflow: hidden;
position: relative;
margin: 200px auto;
border: 2px solid gray;
}
.box ul {
position: absolute;
width: calc(5 * 600px);
list-style: none;
}
.box ul li {
float: left;
height: 300px;
width: 600px;
}
.box ul li img {
width: 100%;
height: 100%;
}
.box p {
position: absolute;
bottom: 0;
left: 210px;
}
.box p span {
display: block;
float: left;
width: 30px;
height:30px;
line-height: 30px;
text-align: center;
border: 2px solid black;
font-size: 20px;
border-radius: 50%;
margin: 10px;
color: blue;
cursor: pointer;
}
.active {
width: 500px;
height: 500px;
background-color: white;
}
</style>
<body>
<div class="box">
</div>
</body>
<script src="jquery-3.6.3.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var imgArr = ["img/轮播图1.jpg", "img/轮播图2.jpg", "img/轮播图3.jpg", "img/轮播图4.jpg"];
var box = $(".box");
var ul = $("<ul></ul>");
box.append(ul);
var p = $("<p></p>");
box.append(p);
for (var i = 0; i < imgArr.length; i++) {
var li = $(`<li><img src=${imgArr[i]}></li>`);
ul.append(li);
var span = $("<span>" + (i+1) + "</span>");
p.append(span);
}
ul.append($(`<li><img src=${imgArr[0]}></li>`))
var allSpan = $(".box p span");
$(allSpan[0]).addClass("active");
var n = 0;
var timer = setInterval(autoPlay, 1000);
function autoPlay() {
n++;
if (n == imgArr.length + 1) {
ul.css({left: 0});
n = 1;
}
ul.animate({
left: -600 * n
}, 1000)
switchSpan();
}
function switchSpan() {
$(allSpan).removeClass('active');
$(allSpan[n%(imgArr.length)]).addClass("active");
}
box.hover(function() {
clearInterval(timer);
}, function() {
timer = setInterval(autoPlay, 2000);
})
allSpan.click(function() {
var index = $(this).index();
n = index;
ul.animate({
left: -600 * index
}, 1000)
switchSpan();
})
</script>
</html>