主要思路

我们需要一个动画函数,他能向左或者向右移动;
当取最后的一个临界的时候,(比如6转向1,将屏幕快速切换到最左边的6)再调用函数动画。
总体预览链接
主要知识点
初始化操作
元素获取
//主要操作动画的元素和每页元素的宽度let target = document.getElementById("main");let target_Width = document.getElementById("container").offsetWidth;// 三个主要的事件let icon = document.getElementsByClassName('icon')[0];let preEle = document.getElementsByClassName("pre")[0];let nextEle = document.getElementsByClassName("next")[0];
全局变量
let currentIndex = 1;let iconsIndex = 1;let time,globTime ; // 全局定时器
- 这里我们希望他能动态的根据元素的多少创建原点,
- 并且为ul元素设置总体的宽度
- 由于我们为了结构在ul的头部多设置了一个li所以需要设置他的left值;
```
(function(){
})();target.style.width = target.children.length * target_Width + 'px';let str = "";for (let i =0 ;i< target.children.length - 2; i++){str += `<div class="icons"><div class="a" data-value = ${i}></div></div>`;}icon .innerHTML = str;icon.children[currentIndex - 1].children[0].classList.add("active")
<a name="S3Dna"></a>### 通过类名操控显示的下标
let addIconClass = function(){ icon.children[iconsIndex -1].children[0].classList.remove(‘active’); icon.children[currentIndex -1].children[0].classList.add(“active”); iconsIndex = currentIndex; };
<a name="BaX4x"></a>### animation动画实现我们不用定义往左或者往右,只需要给出目标的index值就可以了;
/*** 动画* @param index 元素的索引*/let animation = function (index) {clearInterval(globTime);let start = parseInt(target.style.left);let move = 0;let total = - parseFloat(target.style.left) - index * target_Width;let step = Math.ceil(total / 100);addIconClass();console.log( target.style.left);clearInterval(time);// debugger;time = setInterval(function () {move += step;if(Math.abs(move) > Math.abs(total)){// console.log(move , total);target.style.left = total + start +'px';clearInterval(time);globTime = setInterval(moveRight,2000)}else {target.style.left = move + start +'px';}},16);};
<a name="EmvZ3"></a>### 三个控件触发器这里我们将向左的动画抽取出来留作全局的自动播放复用;<a name="UoB6k"></a>#### pre
let moveLeft = function(){if (currentIndex === 1){currentIndex = target.children.length - 1;target.style.left = -(currentIndex * target_Width) + 'px';}animation( -- currentIndex);};preEle.addEventListener('click',moveLeft);
<a name="rRlGK"></a>#### next
let moveRight = function () {if (currentIndex === target.children.length - 2){currentIndex = 0;target.style.left = -(currentIndex * target_Width) + 'px';}animation(++ currentIndex);};nextEle.addEventListener('click',moveRight);
<a name="cYr5r"></a>#### icon
icon.addEventListener("click",function (e) {if (e.target['className'] === 'a'){currentIndex = parseInt(e.target['dataset'].value) + 1;animation(currentIndex)}});
自动播放
globTime = setInterval( moveRight,2000)
真正的妙用不是函数的复用;而是在animation动画那;
如果我们设置一个全局的定时器,让他每隔2s执行一次;那么我们就会发现一个问题;当我们点击一个按钮后定时器还在执行;那我们就会想到在每个函数的开始清空定时器然后函数执行完成再开启它,既然他们都是由animation一起工作的,那么为什么不放在一起呢;这时实际的动画世间就是2s+动画时间,同样的每次操作都会使得icon的下标改变,那么也可以将改变下标的操作一起放到animation中;
