html:
<div class="slider">
<div class="imgs">
<!-- 轮播图默认从第一张开始显示 -->
<img src="./images/banner1.jpg" alt="" data-index="1" class="active" />
<img src="./images/banner2.jpg" alt="" data-index="2" />
<img src="./images/banner3.png" alt="" data-index="3" />
</div>
<!-- 切换按钮数量与图片数量必须一致 -->
<div class="btns">
<span data-index="1" class="active" onclick="setActive()"></span>
<span data-index="2" onclick="setActive()"></span>
<span data-index="3" onclick="setActive()"></span>
</div>
<div class="arrows">
<span class="leftarrow" ><</span>
<span class="rightarrow" >></span>
</div>
</div>
css:
.slider {
max-width: 750px;
min-width: 320px;
margin: auto;
padding: 0 10px;
}
.slider .imgs {
height: 200px;
}
.slider .imgs img {
height: 100%;
width: 100%;
border-radius: 10px;
display: none;
}
.slider .imgs img:hover {
cursor: pointer;
}
.slider .imgs img.active {
display: block;
}
.slider .btns {
display: flex;
place-content: center;
}
.slider .btns span {
width: 8px;
height: 8px;
background-color: rgba(255, 255, 255, 0.4);
border-radius: 50%;
margin: -15px 3px 5px;
}
.slider .btns span.active {
background-color: #fff;
}
.slider .arrows {
display: grid;
grid-template-columns: repeat(2, 20px);
place-content: space-between;
}
.slider .arrows span {
width: 20px;
height: 20px;
background-color: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.6);
margin: -110px 0 5px;
text-align: center;
line-height: 20px;
font-size: larger;
}
.slider .arrows span:hover {
cursor: pointer;
color: #fff;
}
javascript:
const imgs = document.querySelectorAll('.slider .imgs img')
const btns = document.querySelectorAll('.slider .btns span')
// 设置激活状态
function setActive() {
imgs.forEach(img => img.classList.remove('active'));
btns.forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active')
imgs.forEach(img => {
if (img.dataset.index === event.target.dataset.index) {
img.classList.add('active')
}
});
}
// 作业1: 实现鼠标悬停时自动停止播放, 离开时又自动播放
// 要求:轮播图暂停后从暂停位置开始播放
let interval;
beginSlider();
function beginSlider() {
let len=btns.length;
let i=[...btns].findIndex((item)=>item.classList.value=='active');
if (!interval) {
interval = setInterval(()=>{
i++;
i=i<0?len-1:i;
i=i>=len?0:i;
btns[i].dispatchEvent(new Event('click'));
}, 2000);
}
}
function stopSlider() {
clearInterval(interval);
interval=null;
}
const imgbox=document.querySelector(".slider .imgs");
imgbox.addEventListener('mouseover',stopSlider);
imgbox.addEventListener('mouseout',beginSlider);
// 作业2[可选]: 给这个轮播图加上翻页按按钮,实现向前和向后翻页播放
function changeSlider(n){
let len=btns.length;
let i=[...btns].findIndex((item)=>item.classList.value=='active');
i+=n;
i=i<0?len-1:i;
i=i>=len?0:i;
btns[i].dispatchEvent(new Event('click'));
}
document.querySelector(".slider .arrows .leftarrow").addEventListener("click",()=>{changeSlider(-1)});
document.querySelector(".slider .arrows .rightarrow").addEventListener("click",()=>{changeSlider(1)});