当前位置:首页 > Web开发 > 正文

nextIndex);// 获取 index 的差let subIndex = maxIndex - minIndex

2024-03-31 Web开发

使用原生JS实现轮播图,仅需短短几行代码,代码如下

let carousel = new Carousel(); carousel.render({ 'elem': '#carousel', 'data': [ { 'src': '', 'alt': '1', 'title': '1' }, { 'src': '=580/sign=585c22802df5e0feee1889096c6134e5/9726a5d6277f9e2faf4b30911f30e924b999f35e.jpg', 'alt': '2', 'title': '2' }, { 'src': '=1123599174,3662075684&fm=26&gp=0.jpg', 'alt': '3', 'title': '3' }, ], });

固然,不成能这么简单,这里我引入了自界说的 Carousel 类,是使用原生 JS 写的,全部的代码就不放出来了,只给出实现轮播的核心代码

// nextIndex 下一个 index change(nextIndex) { let points = this.points; // 小点点们 let content = this.content; // 主体内容 let items = this.items; // 所有的 item let maxlen = this.data.length; // 数据个数 let thisIndex = this.getThisIndex(); // 当前显示的 index // 获取真实的 nextIndex let realNextIndex = nextIndex; if (nextIndex > maxlen) { realNextIndex = 1; } if (nextIndex < 1) { realNextIndex = maxlen; } // 获取最小 index 最大 index let minIndex = Math.min(thisIndex, nextIndex); let maxIndex = Math.max(thisIndex, nextIndex); // 获取 index 的差 let subIndex = maxIndex - minIndex; // 获取 transform 数据的 index let type = thisIndex > nextIndex; // 界说起始终止 transform let startTransform = type ? String(subIndex * this.itemWidth) : '0'; let endTransform = type ? '0' : String(subIndex * this.itemWidth); // 显示两者及两者之间的 item for (let i = minIndex; i <= maxIndex; i++) { items[i].className = ITEMSHOW; } // 设置起始 transform content.style.transform = `translateX(-${startTransform}%)`; // 给 next 小点点添加 this points[realNextIndex - 1].className = INDITEMTHIS; // 去失之前的小点点的 this points[thisIndex - 1].className = INDITEM; // 给 content 添加 transition 和 transform setTimeout(function () { content.style.transition = 'transform linear .5s'; content.style.transform = `translateX(-${endTransform}%)`; }, 5); // 事情完成后,断根 let timer = setTimeout(function () { // 断根 content 的 transition 和 transform content.style.transition = 'transform linear 0s'; content.style.transform = 'translateX(0)'; // 打消失除 nextItem 之外的其它元素的显示 for (let i = 0; i < items.length; i++) { items[i].className = ITEM; } items[realNextIndex].className = ITEMSHOW; clearTimeout(timer); }.bind(this), 500); }

所有的代码我已经上传到 码云 了,里面有使用要领。
也可以使用百度云下载压缩包(博客园仿佛不能上传)。
链接:https://pan.baidu.com/s/1u5eNjp0iMDVHAJ3U3e5DYg
提取码:ipvq
(注意,下载之后,,文件路径需要改削)

技术图片

原生JS实现轮播图

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/29964.html