class Rotation {
constructor(element) {
this.banner = element.querySelector('.banner')
this.length = this.banner.children.length
this.element = element
this.prevBtn = element.querySelector('.prev')
this.nextBtn = element.querySelector('.next')
this.focusList = this.init()
this.index = 0
this.autoMove()
//调用对应的事件监听
this.handlerChange()
this.handlerFocusClick()
this.handlerMouseBox()
}
init() {
let ol = document.createElement('ol')
//根据对应的个数生成
for (var i = 0; i < this.length; i++) {
if (i == 0) {
ol.innerHTML += `<li class="selected"></li>`
} else {
ol.innerHTML += `<li></li>`
}
}
//添加进去
this.element.appendChild(ol)
//给ul的后面再添加第一个li
//克隆第一个
var clone = this.banner.children[0].cloneNode(true)
this.banner.appendChild(clone)
//返回所有添加的li
return ol.children
}
changePosition(isRight = true) {
if (isRight) {
this.index++
if (this.index == this.banner.children.length) {
//强行设置对应的为第一个
this.banner.style.left = '0px'
//控制对应的下标为0
this.index = 0
}
} else {
this.index--
//如果到第一个应该切到最后一个
if (this.index == -1) {
//强行设置对应的最后一个
this.banner.style.left = this.length * -1 * this.element.clientWidth + 'px'
this.index = this.length - 1
}
}
this.setFocus(this.index)
// move('.banner').set('left', -1*liWidth * index + 'px').end()
// move('.banner').to(-liWidth * index, 0).end()
move(this.banner, {
left: -1 * (this.element.clientWidth) * this.index
}, true)
}
autoMove() {
this.timer = setInterval(() => {
this.changePosition()
}, 2000);
}
setFocus(i) {
//超出范围等于0
if (i > this.length - 1) {
i = 0
}
//小于0 等于最大下标
if (i < 0) {
i = this.length - 1
}
//排他
//先把所有的全部清除 再给自己设置
// 获取所有的ol里面的li
Array.from(this.focusList).forEach((li) => {
li.className = ''
})
this.focusList[i].className = 'selected'
}
//焦点点击事件
handlerFocusClick() {
//事件委托机制
this.focusList[0].parentElement.onclick = (e) => {
e = e || window.event
clearInterval(this.timer)
if (e.target.nodeName == 'LI') {
var i = Array.from(this.focusList).findIndex((li) => {
return li == e.target
})
//移动到对应的位置
move(this.banner, {
left: -this.element.clientWidth * i
}, true)
//将i赋值给index
this.index = i
//切焦点
this.setFocus(i)
// this.autoMove() 导致多一个定时器无法清除
}
}
}
//移动动盒子上面
handlerMouseBox() {
this.banner.parentElement.onmouseenter = () => {
//控制俩个div显示
this.nextBtn.style.display = 'block'
this.prevBtn.style.display = 'block'
//清除动画
clearInterval(this.timer)
}
this.banner.parentElement.onmouseleave = () => {
//控制俩个div隐藏
this.nextBtn.style.display = 'none'
this.prevBtn.style.display = 'none'
//开始动画
this.autoMove()
}
}
//左右切换处理
handlerChange() {
//左边的事件
this.prevBtn.onclick = () => {
this.changePosition(false)
}
//右边的事件
this.nextBtn.onclick = () => {
this.changePosition()
}
}
}
//调用
var box = document.querySelector('.box')
new Rotation(box)