css样式
.box{
width: 1000px;
height: 375px;
margin: 50px auto;
overflow: hidden;
position: relative;
}
.wrap{
width: 4000px;
font-size: 0;
}
img{
width: 1000px;
}
#next,#prev{
width: 41px;
height: 69px;
background-image: url(./images/icon-slides.png);
position: absolute;
top: calc(50% - 34.5px);
}
#next{
background-position: -125px 0;
right: 0;
}
#prev{
background-position: -83px 0;
left: 0;
}
#next:hover{
background-position: -41px 0;
}
#prev:hover{
background-position: 0 0;
}
html代码
<div class="box">
<div class="wrap">
<img src="./images/a.webp" alt="">
<img src="./images/b.jpg" alt="">
<img src="./images/c.webp" alt="">
<img src="./images/d.webp" alt="">
</div>
<div id="next"></div>
<div id="prev"></div>
</div>
js代码
var next = document.getElementById('next');
var wrap = document.getElementsByClassName('wrap')[0];
var x = 0; //记录图片索引
next.onclick = function(){
x++;
if (x == 4) {
x = 0;
}
wrap.style.marginLeft = -1000*x + 'px';
}