js原生轮播图插件制作
【js原生轮播图插件制作】本文实例为大家分享了js原生轮播图插件制作的具体代码,供大家参考,具体内容如下
文章图片
调用时也只需要写一个DIV即可
文章图片
调用的js部分配置内容:
传入轮播图需显示的位置(div)
传入图片和点击跳转的链接
话不多说,上代码
HTML
HTML文档内的
JS插件内容
// 两个参数,第一个轮播图区域,第二个是配置function bannerArea(areaDom, options) {var imgArea = document.createElement("div"); var numberArea = document.createElement("div"); var curIndex = 0; //第几张轮播图var changeTimer = null; var changeDuration = 1000; //间隔var timer = null; initImg(); //创建一个区域来显示图片initNumber(); //创建区域显示角标setStatus(); //设置状态autoChange(); //自动切换 //下面是局部函数 //创建图片,并且设置样式function initImg() {imgArea.style.width = "100%"; imgArea.style.height = "100%"; imgArea.style.display = "flex"; imgArea.style.overflow = "hidden"; for (let i = 0; i < options.length; i++) {var obj = options[i]; var img = document.createElement("img"); img.src = https://www.it610.com/article/obj.imgUrl; img.style.width ="100%"; img.style.height = "100%"; img.style.margin = "0"; img.addEventListener("click", function () {location.href = https://www.it610.com/article/options[i].link; })imgArea.appendChild(img); }imgArea.addEventListener("mouseenter", function () {clearInterval(changeTimer); changeTimer = null; })imgArea.addEventListener("mouseleave", function () {autoChange(); })areaDom.appendChild(imgArea); }//创建角标元素和设置样式function initNumber() {numberArea.style.textAlign = "center"; numberArea.style.marginTop = "-25px"; for (let i = 0; i < options.length; i++) {var sp = document.createElement("span"); sp.style.width = "12px"; sp.style.height = "12px"; sp.style.background = "lightgray"; sp.style.display = "inline-block"; sp.style.margin = "0 7px"; sp.style.borderRadius = "50%"; sp.style.cursor = "pointer"; sp.addEventListener("click", function () {curIndex = i; setStatus(); })numberArea.appendChild(sp); }areaDom.appendChild(numberArea); } //设置角标区域状态function setStatus() {//设置圆圈的背景颜色for (var i = 0; i < options.length; i++) {if (i === curIndex) {//设置背景颜色为选择numberArea.children[i].style.background = "rgb(222 57 57)"; } else {//非选择numberArea.children[i].style.background = "lightgray"; ; } }//显示图片var start = parseInt(imgArea.children[0].style.marginLeft); var end = curIndex * -100; var dis = end - start; var duration = 500; var speed = dis / duration; if (timer) {clearInterval(timer); }timer = setInterval(function () {start += speed * 20; imgArea.children[0].style.marginLeft = start + "%"; if (Math.abs(end - start) < 1) {imgArea.children[0].style.marginLeft = end + "%"; clearInterval(timer); }}, 20)}//自动切换function autoChange() {if (changeTimer) {return; }changeTimer = setInterval(function () {if (curIndex === options.length - 1) {curIndex = 0; } else {curIndex++; }setStatus(); }, changeDuration)} }
轮播图速度(切换时间)可在插件代码中var changeDuration = 1000; //间隔一句里调整
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。