一.css
=二.html和内部js
三.外部js
class SetLoop{
constructor(ele){
this.ele=ele;
this.oUl=ele.querySelector('ul');
this.oUllis=ele.querySelectorAll('ul li');
this.oOl=ele.querySelector('ol');
this.oDa=ele.querySelector('div');
this.index=1;
this.loopTime=0;
this.bool=true;
this.oliwidth=parseInt(window.getComputedStyle(this.oUllis[0]).width);
}
init(){
this.setLi();
this.copyLi();
this.autoLoop();
this.overOut();
this.focus();
this.leftRight();
this.hidden();
}
move(ele,obj,callback){
for(let type in obj){
let oldVal=parseInt(window.getComputedStyle(ele)[type]);
let time=setInterval(()=>{
let val=(obj[type]-oldVal)/4;
val= val>0 ? Math.ceil(val) : Math.floor(val);
oldVal+=val;
ele.style[type]=oldVal+'px';
if(obj[type] ==oldVal){
clearInterval(time);
callback();
}
},100);
}
}
setLi(){
let str='';
this.oUllis.forEach((val,key) => {
if(key == 0){
str+=`<li index="${key+1}" class="active"></li>`;
}else{
str+=`<li index="${key+1}"></li>`;
}
});
this.oOl.innerHTML=str;
}
copyLi(){
let liF=this.oUllis[0];
let liL=this.oUllis[this.oUllis.length-1];
let first=liF.cloneNode(true);
let last=liL.cloneNode(true);
this.oUl.appendChild(first);
this.oUl.insertBefore(last,liF);
this.oUl.style.width=((this.oUllis.length+2)*this.oliwidth)+'px';
this.oUl.style.left=-this.oliwidth+'px';
}
autoLoop(){
this.loopTime=setInterval(()=>{
this.index++;
this.move(this.oUl,{left:-this.index*this.oliwidth},()=>{
this.stopLoop();
});
},3000);
}
stopLoop(){
this.bool=true;
if(this.index==this.oUllis.length+1){
this.index=1;
this.oUl.style.left=(-this.index*this.oliwidth)+'px';
}else if(this.index==0){
this.index=this.oUllis.length;
this.oUl.style.left=(-this.index*this.oliwidth)+'px';
}
let oOllis=this.ele.querySelectorAll('ol li');
oOllis.forEach((val,key)=>{
val.className='';
if(val.getAttribute('index')==this.index){
val.className='active';
}
});
}
overOut(){
this.ele.addEventListener('mouseover',()=>{
clearInterval(this.loopTime);
});
this.ele.addEventListener('mouseOut',()=>{
this.autoLoop();
});
}
focus(){
this.oOl.addEventListener('click',(e)=>{
if(e.target.tagName=='LI'){
if(this.bool != true){
return;
}
this.bool=false;
this.index=e.target.getAttribute('index')-0;
this.move(this.oUl,{left:-this.index*this.oliwidth},()=>{
this.stopLoop();
});
}
});
}
leftRight(){
this.oDa.addEventListener('click',(e)=>{
if(e.target.getAttribute('name')=='left'){
if(this.bool != true){
return;
}
this.bool=false;
this.index--;
this.move(this.oUl,{left:-this.index*this.oliwidth},()=>{
this.stopLoop();
});
}else if(e.target.getAttribute('name')=='right'){
if(this.bool != true){
return;
}
this.bool=false;
this.index++;
this.move(this.oUl,{left:-this.index*this.oliwidth},()=>{
this.stopLoop();
});
}
});
}
hidden(){
document.addEventListener('visibilitychange',()=>{
if(document.visibilityState=='hidden'){
clearInterval(this.loopTime);
}else if(document.visibilityState=='visible'){
this.autoLoop();
}
});
}
}