![](https://i-blog.csdnimg.cn/blog_migrate/9e0ea7121712cef018d7f4c5a359a40b.gif)
一、模拟数据
![](https://i-blog.csdnimg.cn/blog_migrate/9c60205c5acd0ab5f63ba73c0dabe700.png)
二、HTML布局代码
<body>
<div id="box">
<input type="button" id="btn-previous" value="<">
<input type="button" id="btn-next" value=">">
<ul>
<li>
<img>
<p></p>
</li>
<li>
<img>
<p></p>
</li>
<li>
<img>
<p></p>
</li>
<li>
<img>
<p></p>
</li>
</ul>
</div>
</body>
三、css代码
<style>
#box {
width: 700px;
height: 300px;
background-size: 500px 300px;
position: relative;
margin: 100px auto;
border: 1px solid #ccc;
}
#btn-previous {
width: 30px;
position: absolute;
left: 25px;
top: 250px;
}
#btn-next {
width: 30px;
position: absolute;
left: 650px;
top: 250px;
}
li {
list-style: none;
width: 120px;
height: 200px;
margin: 10px;
float: left;
border: 1px solid #656565;
}
ul {
position: absolute;
left: 25px;
top: 20px;
}
img {
width: 120px;
height: 200px;
}
p {
text-align: center;
}
</style>
四、js代码
<script>
class Paging {
constructor(btnNext,btnPrev,lis) {
this.btnNext = btnNext;
this.btnPrev = btnPrev;
this.oLis = lis;
// 第一页
this.index = 0;
this.arr = [];
}
//获取响应数据
getData() {
let that = this;
let xhr = new XMLHttpRequest();
xhr.open("get", "list.json", true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
that.load(xhr.responseText);
}
}
}
load(resText) {
this.arr = JSON.parse(resText);
console.log(this.arr);
this.setBgc();
}
setBgc() {
// 显示4个 往后再走4个
for (var i = this.index * 4, j = 0; i < this.index * 4 + 4; i++, j++) {
this.oLis[j].firstElementChild.src = this.arr[i].img;
this.oLis[j].lastElementChild.innerHTML = this.arr[i].id;
}
}
// 每页的切换
next() {
this.index++;
if (this.index == this.arr.length / 4) {
this.index = 0;
}
this.setBgc();
}
prev() {
this.index--;
if (this.index == -1) {
this.index = this.arr.length / 4 - 1;
}
this.setBgc();
}
eventBind() {
let that = this;
this.btnNext.onclick = function() {
that.next();
}
this.btnPrev.onclick = function() {
that.prev();
}
}
}
let oBtnNext = document.querySelector("#btn-next");
let oBtnPrev = document.querySelector("#btn-previous");
let oLis = document.querySelectorAll("li");
let s = new Paging(oBtnNext,oBtnPrev,oLis);
s.getData();
s.eventBind();
</script>