先上效果图
<body>
<div class="imgbox">
<ul id="items">
<li class="item">
<a href="#"><img src="ad1.jpg"></a>
</li>
<li class="item">
<a href="#"><img src="ad2.jpg"></a>
</li>
<li class="item">
<a href="#"><img src="ad3.jpg"></a>
</li>
</ul>
<button class="left"><</button>
<button class="right">></button>
<div class="footer">
<ul>
<li class="circle"></li>
<li class="circle"></li>
<li class="circle"></li>
</ul>
</div>
</div>
scss:
<style lang="scss">
* {
padding: 0px;
margin: 0px;
}
.imgbox {
width: 500px;
height: 200px;
border: 1px solid;
display: flex;
position: relative;
align-items: center;
.item {
position: absolute;
top: 0px;
width: 500px;
height: 200px;
list-style: none;
opacity: 0;
transition: all 1s;
}
.active {
opacity: 1;
}
.item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.left {
position: absolute;
left: 0px;
}
.right {
position: absolute;
right: 0px;
}
.footer {
position: absolute;
bottom: 10px;
right: 50px;
}
.footer ul {
display: flex;
}
.footer li {
margin: 10px;
}
.active1 {
color: red;
}
}
</style>
js:
<script>
let currentIndex = 0;
let timer = 0;
const imgg = document.querySelectorAll('.item');
const leftg = document.querySelector('.left');
const right = document.querySelector('.right');
const autoli = document.querySelectorAll('.circle');
const length = imgg.length;
// 初始化第一个元素为活动状态
imgg[currentIndex].className = "item active";
autoli[currentIndex].className = "circle active1";
// 节流函数
function throttle(fn, time) {
let temp = false;
return function () {
if (temp) {
return;
} else {
temp = true;
setTimeout(() => {
fn.apply(this, arguments);
temp = false;
}, time);
}
};
}
//显现
function active() {
imgg[currentIndex].className = "item active";
autoli[currentIndex].className = "circle active1";
}
//隐藏
function move() {
autoli[currentIndex].className = "circle ";
imgg[currentIndex].className = "item";
}
//自动和右点击一个原理
function updateImage() {
move();
currentIndex = (currentIndex + 1) % length;
active();
}
// 跟踪自动播放状态
let isAutoPlaying = true;
function pauseAutoPlay() {
isAutoPlaying = false;
clearInterval(timer);
}
function resumeAutoPlay() {
isAutoPlaying = true;
timer = setInterval(updateImage, 3000);
}
leftg.addEventListener('click', throttle(() => {
move();
currentIndex = (currentIndex - 1 + length) % length;
active();
pauseAutoPlay();
}, 700));
right.addEventListener('click', throttle(() => {
updateImage();
pauseAutoPlay();
}, 700));
function auto() {
timer = setInterval(updateImage, 3000);
}
auto();
// 设置一段时间后恢复自动播放
let clickTimeout;
document.addEventListener('click', function () {
//类似防抖,取最后一次点击事件
clearTimeout(clickTimeout);
pauseAutoPlay();
clickTimeout = setTimeout(resumeAutoPlay, 1000);
});
</script>