效果如下:
很丑,但是本来目的就只是实现基本功能而已
CSS:
<style>
* {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
.container {
position: relative;
width: 600px;
height: 400px;
margin: 100px auto 0 auto;
overflow: hidden;
}
.wrap {
position: absolute;
left: 0;
width: 4200px;
height: 400px;
z-index: 1;
}
.container .wrap img {
float: left;
width: 600px;
height: 400px;
}
.container .button {
position: absolute;
right: 50px;
bottom: 20px;
width: 150px;
height: 10px;
z-index: 2;
}
.container .button span {
margin-left: 5px;
display: inline-block;
width: 20px;
height: 20px;
line-height: 20px;
border-radius: 50%;
text-align: center;
color: white;
cursor: pointer;
background-color: green;
}
.container .button span.on {
background-color: red;
}
.span {}
.container .arrow {
position: absolute;
top: 35%;
color: green;
padding: 0 14px;
font-size: 50px;
z-index: 2;
display: none;
}
.container .arrow-left {
left: 10px;
}
.container .arrow-right {
right: 10px;
}
.container:hover .arrow {
display: block;
}
.container .arrow:hover {
background-color: rgba(0,0,0,0.2);
}
</style>
HTML:
<div class="container">
<div class="wrap">
<img src="./images/1.png" alt="">
<img src="./images/2.png" alt="">
<img src="./images/3.png" alt="">
<img src="./images/4.jpg" alt="">
<img src="./images/5.jpg" alt="">
</div>
<div class="button">
<span class="span">1</span>
<span class="span">2</span>
<span class="span">3</span>
<span class="span">4</span>
<span class="span">5</span>
</div>
<a href="javascript:;" class="arrow arrow-left"><</a>
<a href="javascript:;" class="arrow arrow-right">></a>
</div>
JS:
<script>
let wrap = document.querySelector(".wrap");
let next = document.querySelector(".arrow-right");
let prev = document.querySelector(".arrow-left");
let container = document.querySelector(".container");
let buttons = document.querySelectorAll(".span");
let timer = null;
let index = 0;
next.onclick = function () {
nextPic();
};
prev.onclick = function () {
prevPic();
};
function nextPic() {
let newLeft;
if (wrap.offsetLeft === -2400) { // 每一张图片的宽度是600px,第一张时left值为0,最后一张自然为2400
newLeft = 0;
} else {
newLeft = parseInt(wrap.offsetLeft) - 600;
}
wrap.style.left = newLeft + "px";
if (index === 4) { // 用于图片的顺序和序号的同步
index = 0;
} else {
index++;
}
showIndex();
}
function prevPic() {
let newLeft;
if (wrap.offsetLeft === 0) {
newLeft = -2400;
} else {
newLeft = parseInt(wrap.offsetLeft) + 600;
}
wrap.style.left = newLeft + "px";
if (index === 0) {
index = 4;
} else {
index--;
}
showIndex();
}
function autoPlay () {
timer = setInterval(() => {
nextPic();
}, 2000);
}
autoPlay();
container.onmouseenter = function () {
clearInterval(timer);
};
container.onmouseleave = function () {
autoPlay();
};
function showIndex() {
for (let i = 0; i < buttons.length; i++) {
buttons[i].className = ""
}
buttons[index].className = "on";
}
</script>