js轮播图的简易封装案例
<script>
//初始化
let imglist = [
"imgs/1.jpg",
"imgs/2.jpg",
"imgs/3.jpg",
"imgs/4.jpg",
]
let lunbo = {
leftBtn: document.querySelector(".left"),
rigthBtn: document.querySelector(".rigth"),
ul: document.querySelector(".list"),
current: 0,
ln: imglist.length,
//初始化页面布局
init: function () {
let str = ""
imglist.forEach(img => {
str += `<li><img src="${img}" alt=""></li>`
this.ul.innerHTML = str
this.ul.style.width = `${570 * this.ln}px`//设置ul的宽度
})
},
//轮播图移动状态
register: function () {
this.rigthBtn.onclick = () => {
if (this.current === this.ln - 1) {
this.current = -1
}
this.current++
this.ul.style.transform = `translateX(${-570 * this.current}px)`
}
this.leftBtn.onclick = () => {//箭头函数强行绑定上下文
if (this.current === 0) {
this.current = this.ln
}
this.current--
this.ul.style.transform = `translateX(${-570 * this.current}px)`
}
},
}
lunbo.init()
lunbo.register()
</script>