原理示意图
具体思路就是将数组最后一项的位置移到第一项的位置,其余项的位置也向后移。
数组改变代码
javascript">//装图片的盒子数组
const carouselItems = document.getElementsByClassName("carousel-item");
//盒子数组长度
let length = carouselItems.length;
//carousel.currentIndex初始为0
let index = carousel.currentIndex = ++carousel.currentIndex % length;
let newArr = Array.from(carouselItems);
// console.log(`${newArr = [...newArr.slice(0)]}`);
let lens = newArr.length;
// 返回元素矩形范围,屏幕坐标,若成功获取返回RECT类型,否则返回None
//改变数组排序
index != 0 && (newArr = [...newArr.slice(-index, lens), ...newArr.slice(0, length - index)]);
newArr.forEach((item, i) => {
// if (i == 0) {
// item.style.opacity = 0;
// // item.style.tranform = `translateX(${-width * (length - 1)}px)`;
// // // item.style.opacity = 0;
// }
item.style.transform = `translateX(${width * (i - 1)}px)`;
item.style.opacity = 1;
})
slice方法
如果slice第一个参数为负数,代表从结尾开始,例如
javascript">const arr = [1,2,3,4];
arr.slice(-1,arr.length);//[4]
arr.slice(-2,arr.length);//[3,4]
arr.slice(-3,arr.length);//[2,3,4]
将数组元素描述为[1,2,3,4]
javascript">newArr = [...newArr.slice(-index, lens), ...newArr.slice(0, length - index)]);
数组改变依次为
javascript">//index = 0 初始状态
[1,2,3,4]
//index = 1
[[4][1,2,3]]
//index = 2
[[3,4][1,2]]
//index = 3
[[2,3,4][1]]
//index = 4
[[1,2,3,4][]]
index数值与显示的关系为
以初始状态 2所在位置为0,假设每个元素宽为w
则初始的位置关系为
当index++,变为1后,数组变化为
javascript">[1,2,3,4] -> [[4][1,2,3]]
根据位置变化代码
javascript">newArr.forEach((item, i) => {
// if (i == 0) {
// // item.style.tranform = `translateX(${-width * (length - 1)}px)`;
// // // item.style.opacity = 0;
// }
item.style.transform = `translateX(${width * (i - 1)}px)`;
item.style.opacity = 1;
})
变化后元素4的下标为0,位置由 初始的2w 变为 -w
则元素1的位置由 初始-w 变为 0(此时元素1展示)
元素2,3同理
下一次重新获取数组
javascript">const carouselItems = document.getElementsByClassName("carousel-item");
得到的依然是
javascript">[1,2,3,4]
但是这些元素对象的位置却是变化过的
当index变为2,数组变化为
javascript">[1,2,3,4] -> [[3,4][1,2]]
再根据下标位置改变元素位置。
最终从视觉角度看就是index变化一次,最后一项元素的位置就会变为 -w,相当于变为第一项,其余元素在其本来的位置上向右移动w,相当于向后移动。但是数组的元素其实是没有变化,只是改变了元素在视觉上看到的其所在的位置。