<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wraper {
width: 500px;
height: 300px;
position: relative;
}
.wraper>img {
width: 500px;
height: 300px;
display: none;
}
.circle {
position: absolute;
bottom: 20px;
left: calc(50% - 60px);
}
span {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
background-color: rgba(100, 100, 100, 0.8);
}
.active_circle {
background-color: #ccc;
}
.wraper>.active {
display: block;
}
#pre {
width: 30px;
height: 50px;
background-color: rgba(100, 100, 100, 0.8);
color: #fff;
position: absolute;
left: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
#next {
width: 30px;
height: 50px;
background-color: rgba(100, 100, 100, 0.8);
color: #fff;
position: absolute;
right: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
</style>
</head>
<body>
<div class="wraper">
<img class="active" src="./img/1.jpg" alt="">
<img src="./img/2.jpg" alt="">
<img src="./img/3.jpg" alt="">
<img src="./img/4.jpg" alt="">
<div id="pre">
<</div> <div id="next">>
</div>
<div class="circle">
<span class="active_circle"></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script>
var pre = document.getElementById("pre");
var next = document.getElementById("next");
var imgs = document.getElementsByTagName("img");
var spans = document.getElementsByTagName("span");
// 计数器:点击上一个计数器++ 下一个计数器
var count = 0;
pre.onclick = function () {
// 清空默认样式
clearStyle(imgs, spans);
--count;
if (count < 0) {
count = imgs.length - 1;
}
imgs[count].className = "active";
spans[count].className = "active_circle";
};
// 清空默认样式
function clearStyle(arr, spans) {
for (var i = 0; i < arr.length; i++) {
arr[i].className = "";
spans[i].className = "";
}
}
next.onclick = function () {
++count;
clearStyle(imgs, spans);//清空图片与小圆点的默认样式
// 限制count 最大值是imgs.length - 1
if (count >imgs.length - 1) {
count = 0;
}
// 点击下一张切换图片
imgs[count].className = "active";
// 点击下一个小圆点切换到下一个
spans[count].className = "active_circle";
};
// 点击小圆点切换图片同时改变count值
for (var i = 0; i < spans.length; i++) {
spans[i].i = i;//记录用户点击的是哪一个小圆点
//给每个小圆点绑定点击事件
spans[i].onclick = function () {
var index = this.i;//保存当前点击小圆点的索引值
count = index;//保证上一个下一个顺序不会乱
clearStyle(imgs, spans);//清空图片和小圆点的默认样式
this.className = 'active_circle';//给当前点击的小圆点添加样式
imgs[index].className = 'active';//显示对应图片
}
}
</script>
</body>
</html>
轮播
最新推荐文章于 2024-06-23 22:34:25 发布