1.封装一个缓动动画
function animation(obj,target,call){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
let step = (target/obj.offsetLeft)/10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if(obj.offsetLeft === target){
clearInterval(obj.timer);
call && call();
}
obj.style.left = obj.offsetLeft + step;
},20)
}
2.获取元素、父盒子实际宽度
let fatherWidth = father.offsetWidth;
3.鼠标经过模块,左右按钮显示,并清除定时器;离开隐藏左右按钮,恢复定时器
father.addEventListern("mouseenter",function(){
btn_l.style.display = "block";
btn_r.style.display = "block";
clearIntval(tiemr);
timer = null;
})
father.addEventListern("mouseleave",function(){
btn_l.style.display = "none";
btn_r.style.display = "none";
timer = setIntval(function(){
btn_r.click();
},2000)
})
4.动态生成小圆点,给小圆点添加动态点击事件,封装一个控制小圆点样式的函数
for(let i = 0;i < ul.children.length;i ++){
let li = document.createElement("li");
li.setAttribute("index",i);
ol.appendChild(li);
li.addEventListern("click",function(){
for(let j = 0;j < ol.children.length;j ++){
//清空小圆点样式
ol.children[j].className = "";
}
this.className = "active";
let ind = this.getAttribute("index");
num = ind;
circle = ind;
animation(ul,-ind*fatherWidth);
})
}
ol.children[0].className = "active";
//控制小圆点样式
function circleChange(circle){
for(let i = 0;i < ol.children.length;i ++){
ol.children[i].className = "";
}
ol.children[circle].className = "active";
}
5.因为每一张或最后一张会立即跳走,所以要把第一张克隆在最后
let first=ul.children[0].cloneNode(true);
ul.appendChild(first);
6.点击右侧按钮,图片向左轮播,左侧同理(使用节流)
btn_r.addEventListener('click',function(){
if(flag){
flag=false;
if(num===ul.children.length-1){
ul.style.left=0;
num=0;
}
num++;
animate(ul,-num*focusWidth,function(){
flag=true;
});
circle++;
if(circle==ol.children.length){
circle=0;
}
circleChange(circle);
}
})
7.自动播放
let timer=this.setInterval(function(){
btn_r.click();
},2000)
})