点击左右按钮实现轮播图切换图片
style:
*{
margin: 0;
padding: 0;
margin: auto;
}
#img1{
width: 300px;
height: 300px;
position: relative;
}
#butto1{
width: 50px;
height: 100px;
font-size: 50px;
border: none;
background-color: hsla(0, 0%, 0%, 0.2);
position: absolute;
top: 100px;
left: 0px;
color: aquamarine;
}
#butto2{
width: 50px;
height: 100px;
font-size: 50px;
border: none;
background-color: hsla(0, 0%, 0%, 0.2);
position: absolute;
top: 100px;
left: 250px;
color: aquamarine;
}
html:
<div>
<img id="img1" src="https://d-ssl.dtstatic.com/uploads/blog/202402/01/V2SoD3v1HmgwjZ6.thumb.1000_0.jpg_webp" alt="">
<button id="butto1"><</button>
<button id="butto2">></button>
</div>
style:
var imgss = document.getElementById("img1");
var button1 = document.getElementById("butto1");
var button2 = document.getElementById("butto2");
var index = 0;
var images = [
"https://d-ssl.dtstatic.com/uploads/blog/202402/01/V2SoD3v1HmgwjZ6.thumb.1000_0.jpg_webp",
"https://d-ssl.dtstatic.com/uploads/blog/202402/01/JOS3dXY9TWDA04e.thumb.1000_0.jpg_webp",
"https://d-ssl.dtstatic.com/uploads/blog/202402/01/0GSP0XdvS0qgy3D.thumb.1000_0.jpg_webp",
"https://d-ssl.dtstatic.com/uploads/blog/202402/01/N5SoxNdwHPypJ1p.thumb.1000_0.jpg_webp"
];
button1.addEventListener("click", function () {
index--;
if (index < 0) {
index = images.length - 1;
}
imgss.src = images[index];
});
button2.addEventListener("click", function () {
index++;
if (index >= images.length) {
index = 0;
}
imgss.src = images[index];
});