<style>
* {
margin: 0;
padding: 0;
}
ul,ol,li{
list-style: none;
}
img{
width: 100%;
height: 100%;
display: block;
}
.banner {
width: 100%;
height: 500px;
position: relative;
margin: 50px 0;
}
.banner > ul {
width: 100%;
height: 100%;
position: relative;
}
.banner >ul > li{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
opacity: 0;
transition: opacity .5s linear;
}
.banner > ul >li.active{
opacity: 1;
}
.banner > ol{
width: 200px;
height: 30px;
position: absolute;
left: 30px;
bottom: 30px;
background-color: rgba(0, 0, 0, 3);
display: flex;
justify-content: space-around;
align-items: center;
border-radius: 15%;
}
.banner > ol > li{
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
cursor: pointer;
}
.banner > ol > li.active{
background-color: orange;
}
.banner > div{
width: 40px;
height: 60px;
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 5);
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
color: #fff;
}
.banner > div.left{
left: 0;
}
.banner > div.right{
right: 0;
}
</style>
</head>
<body>
<div class="banner">
<!-- 图片区域 -->
<ul class="imgBox">
<li class="active"><img src="/img/星空.jpg" alt=""></li>
<li><img src="/img/女孩 精灵 尖耳朵 蓝眼 项链 4K高清壁纸_1920x1080_4kbizhi.com.jpg" alt=""></li>
<li><img src="/img/58e07420d86f32e31fe83e71390d213fa25166f8.jpg@942w_531h_progressive.webp" alt=""></li>
<li><img src="/img/005250-1637340770973a.jpg" alt=""></li>
</ul>
<!-- 焦点区域 -->
<ol>
<li data-i="0" data-name="point" class="active"></li>
<li data-i="1" data-name="point"></li>
<li data-i="2" data-name="point"></li>
<li data-i="3" data-name="point"></li>
</ol>
<!-- 左右按钮 -->
<div class="left"><</div>
<div class="right">></div>
</div>
<script>
// 获取到所有承载图片的 li 和所有承载焦点的 li
var imgs = document.querySelectorAll("ul >li");
var points = document.querySelectorAll("ol > li");
var banner = document.querySelector(".banner");
// 准备一个变量,表示当前是第几张,默认是 0 ,因为默认显示的是索引第0张
var index = 0;
// 书写一个切换一张的函数
// 约定:
// 参数为 true ,我们切换下一张
// 参数为 false,我们切换上一张
// 参数为 数字,我们切换到指定索引的那一张
function changOne(type) {
// 让当前这一张消失
imgs[index].className = " ";
points[index].className = " ";
// 根据 type 传递来的参数,来切换 index 的值
if (type === true) {
index++;
}else if(type === false){
index--;
}else{
index = type;
}
// 判定一下 infex 的边界值
if (index >= imgs.length) {
index = 0;
}
if(index < 0){
index = imgs.length - 1;
}
// 让改变后的这一章显示出来
imgs[index].className = "active";
points[index].className = "active";
}
// 给 轮播图区域 盒子绑定点击事件
banner.onclick = function(e){
// 判断点击的是左按钮
if (e.target.className === "left") {
// 切换上一张,调用 changOne 方法传递参数为false
changOne(false)
}
// 判断点击的是右按钮
if (e.target.className === "right") {
// 切换下一张,调用 changOne 方法传递参数为true
changOne(true);
}
// 判断点击的是焦点盒子
if (e.target.dataset.name === "point") {
// 拿到自己身上记录的索引
var i = e.target.dataset.i - 0;
// 切换某一张,调用 changOne 方法传递参数为要切换的索引
changOne(i);
}
}
</script>
</body>
JavaScript练习小案例-----轮播图
最新推荐文章于 2024-07-20 23:54:17 发布