JS轮播图的n种方法
第一种
第一种轮播图,没有耳朵,自动轮播,鼠标放上去会停止,只需在body里面更改图片宽高和图片路径 * { margin: 0; padding: 0; list-style: none; } .wrap { margin: 60px auto; overflow: hidden; position: relative; margin: 100px auto; } .wrap ul { position: absolute; width: 100%; height: 100%; } .wrap ul li { height: 100%; } .wrap ul li img { width: 100%; height: 100%; } .wrap ol { position: absolute; width: inherit; display: flex; justify-content: center; bottom: 10px; } .wrap ol li { height: 5px; width: 30px; background: #c5c0c0; border-radius: 10px; margin-left: 5px; float: left; line-height: center; text-align: center; cursor: pointer; } .wrap ol .on { background: white; } window.onload = function () { var wrap = document.getElementsByClassName('wrap')[0], pic = document.getElementById('pic').getElementsByTagName("li"), list = document.getElementById('list').getElementsByTagName('li'), index = 0, timer = null; // 定义并调用自动播放函数 timer = setInterval(autoPlay, 2000); // 鼠标划过整个容器时停止自动播放 wrap.onmouseover = function () { clearInterval(timer); } // 鼠标离开整个容器时继续播放至下一张 wrap.onmouseout = function () { timer = setInterval(autoPlay, 2000); } // 遍历所有数字导航实现划过切换至对应的图片 for (var i = 0; i = pic.length) index = 0; changePic(index); } // 定义图片切换函数 function changePic(curIndex) { for (var i = 0; i < pic.length; ++i) { pic[i].style.display = "none"; list[i].className = ""; } pic[curIndex].style.display = "block"; list[curIndex].className = "on"; } };
第二种
第二种轮播图,有耳朵,功能基本齐全,只需在body里面更改图片宽高和图片路径
第二种轮播图,有耳朵,功能基本齐全,只需在body里面更改图片宽高和图片路径 #mlBox { position: relative; margin: 50px auto; border: 1px #ececec solid; } #mlImg { width: 100%; height: 100%; } #mlImg img { width: 100%; height: 100%; display: none; } #mlSpan { width: inherit; height: 10px; position: absolute; bottom: 10px; display: flex; justify-content: center; } #mlSpan span { display: block; float: left; width: 32px; height: 4px; background: white; border-radius: 2px; margin: 0 2px; z-index: 100; opacity: 0.4; } #mlImg #mlShow { display: block; } #mlSpan #mlOn { opacity: 1; } #mlLeft { width: 30px; height: 30px; background: rgb(245, 245, 245, 0.3); position: absolute; border-radius: 50%; left: 0; top: 47%; display: none; text-align: center; line-height: 30px; } #mlRight { width: 30px; height: 30px; background: rgb(245, 245, 245, 0.3); position: absolute; border-radius: 50%; right: 0; top: 47%; display: none; text-align: center; line-height: 30px; } #mlLeft span, #mlRight span { color: rgb(255, 255, 255); } #mlLeft:hover { background: rgb(245, 245, 245, 0.7); } #mlRight:hover { background: rgb(245, 245, 245, 0.7); }
< > ml(true); //调用ml函数 注:传参是否需要左右指示 默认false function ml(indicator) { var oMlBox = document.getElementById('mlBox'); //获取id:mlBox var oMlImg = document.getElementById('mlImg'); //获取id:mlImg var oMlSpan = document.getElementById('mlSpan'); //获取id:mlSpan var aSpan = oMlSpan.getElementsByTagName('span'); //获取id:mlSpan里面的span标签 var aImg = oMlImg.getElementsByTagName('img'); //获取id:mlImg里面的img标签 var oMlLeft = document.getElementById('mlLeft'); //获取id:mlLeft var oMlRight = document.getElementById('mlRight'); //获取id:mlRight var u = 0; //当前照片位置 var shut = null; //定时器的名字 function f1() { for (var i = 0; i < aSpan.length; i++) { //循环id:mlSpan里面的span标签 aSpan[i].id = ''; //让span标签的id等于空 aImg[i].id = ''; //让id:mlImg里面img标签id等空 } aSpan[u].id = 'mlOn'; //当前位置的span标签id等于mlOn aImg[u].id = 'mlShow'; //当前位置的img标签id等于mlShow } for (var f = 0; f = aImg.length) { //当前位置大于照片的数量就等于0u = 0; } f1(); //调用f1函数 }; oMlLeft.onclick = function () { //点击左指示 u--; //当前位置减一 if (u = aImg.length) { //当前位置大于等于照片的数量当前位置等于0 u = 0; } f1(); //调用f1函数 }, 3000); } f2(); //调用f2函数 }
第三种
第三种轮播图,功能也基本齐全,问题是图片多宽就得多款,否则容易出问题,要改匿名函数里面的循环值,在body里面改宽高和路径
第三种轮播图,功能也基本齐全,问题是图片多宽就得多款,否则容易出问题,要改匿名函数里面的循环值,在body里面改宽高和路径 * { margin: 0; padding: 0; text-decoration: none; } #container { margin: 20px auto; overflow: hidden; position: relative; } #list { height: 100%; width: 30000px; position: absolute; z-index: 1; } img { display: block; float: left; } #buttons { position: absolute; width: inherit; height: 10px; z-index: 2; bottom: 25px; display: flex; justify-content: center; } #buttons span { float: left; border: 1px solid #fff; width: 10px; height: 10px; border-radius: 50%; margin: 0 5px; color: #333; cursor: pointer; } #buttons .on { background: white; } .arrow { cursor: pointer; display: none; width: 30px; height: 30px; position: absolute; z-index: 2; top: 45%; background-color: RGBA(0, 0, 0, .2); border-radius: 50%; } .arrow:hover { background-color: RGBA(0, 0, 0, .5); } #container:hover .arrow { display: block; } #prev { left: 10px; } #next { right: 10px; } (function (window, document) { // 默认的图片宽高 let defaultSetting = { "width": "500", "height": "500" } function Carousel(options) { var self = this; self.setting = Object.assign(defaultSetting, options); self.container = document.querySelector(self.setting.container); // 设置container的宽高,才能看到,否则一篇空白 self.container.style.width = options.width + 'px'; self.container.style.height = options.height + 'px'; self.list = document.querySelector("#list"); self.sliderItems = self.list.getElementsByTagName('img'); self.buttons = document.querySelector("#buttons").getElementsByTagName('span'); self.prev = document.querySelector("#prev"); self.next = document.querySelector("#next"); self.index = 1; self.prev.onclick = function () { // 点击按钮调用rotate方法切换到上一张 self.rotate('left'); } self.next.onclick = function () { // 点击按钮调用rotate方法切换到下一张 self.rotate('right'); } // 打开页面就循环轮播 } Carousel.prototype = { rotate: function (dir) { // 定义rotate方法 let self = this; let newLeft; // 变化后的left值 let selfLeft = self.list.style.left; // 原left值 let sliderWidth = parseInt(self.setting.width); // 可见视口宽度,这里也是一张图片宽度 let len = self.sliderItems.length; // 图片总张数 let totalWidth = len * sliderWidth // 点击左按钮,往前一张 if (dir === 'left') { if (!selfLeft) {newLeft = selfLeft + sliderWidth; } else {newLeft = parseInt(selfLeft) + sliderWidthself.index--; } if (newLeft > 0) { // 如果是第一张图片往前切换,则切换到最后一张newLeft = -totalWidth + sliderWidth;self.index = len; } self.list.style.left = newLeft + 'px' // 改变left值 showButtons(); } // 点击右按钮,往后一张, 则left值增加一个负sliderWidth if (dir === 'right') { if (!selfLeft) {newLeft = selfLeft - sliderWidthself.index++; } else {newLeft = parseInt(selfLeft) - sliderWidthself.index++; } if (newLeft <= -totalWidth) {newLeft = 0;self.index = 1; } self.list.style.left = newLeft + 'px' // 改变left值 showButtons(); } function showButtons() { // rotate方法里面又定义了showButtons方法 for (let i = 0; i < self.buttons.length; i++) {if (self.buttons[i].className === 'on') { self.buttons[i].className = ''; // 清除原圆点高亮状态 break;} } self.buttons[self.index - 1].className = 'on'; } } } window.Carousel = Carousel; // 暴露出去,供全局对象使用 })(window, document);
第四种
第四种轮播图,功能也挺齐全,适合图片宽的,问题是下面滚动的小圆点没变色
第四种轮播图,功能也挺齐全,适合图片宽的,问题是下面滚动的小圆点没变色 * {margin: 0;padding: 0;}li {list-style: none;}.box {margin: 20px auto;display: flex;align-items: center;position: relative;overflow: hidden;}.box>* {position: absolute;}.side-btns {width: inherit;height: 100px;display: flex;justify-content: space-between;z-index: 2;}.side-btns>div {width: 50px;height: inherit;text-align: center;line-height: 100px;font-size: 18px;background-color: rgba(0, 0, 0, .3);color: white;cursor: pointer;user-select: none;}.btns {width: inherit;height: 20px;display: flex;justify-content: center;z-index: 2;position: absolute;bottom: 20px;}.btns>li {width: 16px;height: 16px;border-radius: 50%;margin-right: 12px;cursor: pointer;background-color: rgba(0, 0, 0, .4);}.btn>li .on {background-color: white;}.wins {width: 100%;height: 100%;display: flex;}.wins>li {width: 100%;height: 100%;flex-grow: 0;flex-shrink: 0;}.wins>li img {width: 100%;height: 100%;}(function(window, undefined) {// 获取元素css属性值function getCss(elem, attr) {return elem.currentStyle ?elem.currentStyle[attr] :window.getComputedStyle(elem, null)[attr];}// 去除字符串中的非数字,不包括负号function toInt(str) {var rex = /[^0-9]/ig;return Number((str[0] === '-' && str[1] !== '=') ? '-' + str.replace(rex, '') : str.replace(rex, ''));}// 封装动画函数,参数:dom对象、css属性值对象、动画执行时间、动画完成后回调function animation(elem, params, speed, callback) {for(var param in params) {(function(param) {var elemValue = toInt(getCss(elem, param)),targetValue = toInt(params[param]),currentDis = elemValue,unit = params[param].substr(params[param].indexOf('[A-Za-z]+') - 1);if(params[param].length > 2) {var prefix = params[param].substr(0, 2);if(prefix === '+=')targetValue = elemValue + targetValue;else if(prefix === '-=')targetValue = elemValue - targetValue;}var dis = (targetValue - elemValue) / speed,sizeFlag = targetValue < elemValue;var timer = setInterval(function() {elemValue = toInt(getCss(elem, param));if(sizeFlag) {if(currentDis = targetValue) {clearInterval(timer);elem.style[param] = targetValue + unit;} else {currentDis += dis;elem.style[param] = currentDis + unit;}}}, 1);})(param);}if(typeof callback === 'function') {callback();}};// 向右轮播数组移动function rightRoundArrayMove() {var winsLen = wins.length;var lastWin = wins[winsLen - 1];for(var i = winsLen - 1; i > 0; i--) {wins[i] = wins[i - 1];}wins[0] = lastWin;}// 向左轮播function rightRound(time) {rightRoundArrayMove();wins.forEach(function(win, index) {(index === 0) ?win.style.left = index * winWidth - winWidth + 'px':animation(win, {left: '+=' + winWidth + 'px'}, time ? time : animationTime);});}// 向右轮播function leftRound(time) {var winsLen = wins.length;var firstWin = wins[0];for(var i = 0; i < winsLen - 1; i++) {wins[i] = wins[i + 1];}wins[winsLen - 1] = firstWin;wins.forEach(function(win, index) {(index === wins.length - 1) ?win.style.left = index * winWidth - winWidth + 'px':animation(win, {left: '-=' + winWidth + 'px'}, time ? time : animationTime);});}var// wins, btns, sbtns用于保存构造函数的参数wins,btns,sbtns,// 窗口的宽度winWidth,// 过渡动画时间(毫秒),默认为100animationTime = 100,// 点击按钮轮播间隔clickInterval = animationTime << 2,// 保存自动轮播定时器、定时器间隔、是否向右轮播autoRoundTimer,qinterval,qisRight,// slide构造函数,参数:窗口数组,按钮数组,侧边按钮数组slide = function(wins, btns, sbtns) {return new slide.prototype.init(wins, btns, sbtns);};slide.prototype = {// 初始化窗口元素init: function(awins, abtns, asbtns) {if(!awins) {throw new Error('The window array cannot be empty.');}wins = Object.values(awins), btns = abtns, sbtns = asbtns;// 处理窗口少于3个的情况if(wins.length === 1) {var winParent = wins[0].parentNode;var winHTML = wins[0].outerHTML;winParent.innerHTML += winHTML + winHTML;wins = Object.values(winParent.children);} else if(wins.length === 2) {var winParent = wins[0].parentNode;winParent.innerHTML += wins[0].outerHTML + wins[1].outerHTML;wins = Object.values(winParent.children);}winWidth = wins[0].offsetWidth;wins.forEach(function(win, index) {win.style.position = 'absolute';win.index = index;});rightRoundArrayMove();wins.forEach(function(win, index) {win.style.left = index * winWidth - winWidth + 'px';});},// 设置过渡动画时间setAnimationTime: function(time) {animationTime = time;clickInterval = animationTime << 2;},// 自动轮播,参数:轮播时间间隔、是否为向右轮播autoRound: function(interval, isRight) {autoRoundTimer = setInterval(function() {isRight ? rightRound() : leftRound();}, interval);qinterval = interval;qisRight = isRight;},// 侧边按钮点击,参数为侧边按钮元素数组,该参数可在构造函数中传递或现在传递sideBtnClickRound: function(sabtns) {var leftBtn = sabtns ? sabtns[0] : sbtns[0],rightBtn = sabtns ? sabtns[1] : sbtns[1];var isclick = true;leftBtn.onclick = function() {if(isclick) {isclick = false;rightRound();setTimeout(function() {isclick = true;}, clickInterval);}};rightBtn.onclick = function() {if(isclick) {isclick = false;leftRound();setTimeout(function() {isclick = true;}, clickInterval);}};},// 普通按钮点击,参数:普通按钮数组、回调btnsClickRound: function(abtns, callback) {var ibtns = abtns ? abtns : btns;var isclick = true;ibtns.forEach(function(btn, index) {btn.onclick = function() {if(isclick) {isclick = false;if(typeof callback === 'function') {callback(ibtns, btn, index);}var poor = index - wins[1].index;var count = Math.abs(poor);if(poor 0) {var timer = setInterval(function() {leftRound(animationTime / (poor + 2));if((--count) === 0)clearInterval(timer);}, animationTime);}setTimeout(function() {isclick = true;}, clickInterval << 1);}}});},// 设置鼠标移入取消自动轮播,参数:移入的元素、移入元素回调、移出元素回调setOverStop: function(box, overCallback, outCallback) {box.onmouseover = function(e) {clearInterval(autoRoundTimer);if(typeof overCallback === 'function') {overCallback(e);}}box.onmouseout = function(e) {slide.prototype.autoRound(qinterval, qisRight);if(typeof outCallback === 'function') {outCallback(e);}}}}slide.prototype.init.prototype = slide.prototype;window.slide = _slide = slide;})(window);window.onload = function() {var wins = document.querySelectorAll('.wins > li');var btns = document.querySelectorAll('.btns > li');var sideBtns = document.querySelectorAll('.side-btns > div');var box = document.querySelector('.box');var s = slide(wins, btns, sideBtns); // 创建轮播对象,参数:窗口dom数组、下方按钮dom数组(可选)、s.autoRound(2000); // 设置自动轮播s.setAnimationTime(200); // 设置过渡动画时间s.setOverStop(box); // 设置鼠标移入元素时自动轮播停止,参数:移入的dom元素、移入元素回调、移出元素回调s.sideBtnClickRound(); // 设置点击侧边按钮时轮播,参数:按钮dom数组(可选)s.btnsClickRound(); // 设置下方按钮点击时轮播,参数:按钮dom数组(可选)、回调}<>
<!-- -->
第五种
第五种轮播图,功能也基本齐全,问题是图片多宽就得多款,否则容易出问题,要改匿名函数里面的循环值,在body里面改宽高和路径
第五种轮播图,功能也基本齐全,问题是图片多宽就得多款,否则容易出问题,要改匿名函数里面的循环值,在body里面改宽高和路径 * { margin: 0; padding: 0; } ul, li { list-style: none; } .container { margin: 100px auto; position: relative; overflow: hidden; } .slide { float: left; } img { display: block; } .pagination { width: 160px; position: absolute; bottom: 30px; margin-left: -80px; left: 50%; } .pagination li { float: left; width: 20px; height: 20px; background-color: rgb(0, 0, 0, .2); margin: 0 10px; border-radius: 50%; } .button-pre, .button-next { width: 22px; height: 40px; position: absolute; top: 50%; margin-top: -20px; } .button-pre { left: 10px; width: 30px; height: 30px; background-color: rgb(0, 0, 0, .2); border-radius: 50%; /* background: url('../image/left.png') no-repeat center center; */ } .button-next { right: 10px; width: 30px; height: 30px; background-color: rgb(0, 0, 0, .2); border-radius: 50%; /* background: url('../image/right.png') no-repeat center center; */ } .button-pre:hover, .button-next:hover{ background-color: rgb(0, 0, 0, .5); } .pagination .active { background-color: white; } ; (function ($) { // 默认设置 var defaults = { speed: 1000, interval: 2000, width: '324', height: '324' } function Banner(ele, options) { // 获得container元素, 设置container的宽高,才能看到,否则一篇空白 this.container = document.querySelector('.mycontainer'); this.container.style.width = options.width + 'px'; this.container.style.height = options.height + 'px'; // 获取元素对象 this.element = $(ele); // 合并设置项 this.options = $.extend({}, defaults, options); // 获取包裹图片的父元素 this.wrapper = this.element.children().first(); // 获取要克隆的元素 this.firstChild = this.wrapper.find('.slide:first'); // 获取一张图片宽度 this.Width = this.firstChild.width(); // 记录图片下标 this.n = 0; // 获取图片个数 this.len = this.wrapper.find('.slide').length; // 获取切换导航按钮 this.prev = this.element.find('.button-pre'); this.next = this.element.find('.button-next'); // 获取分页器 this.pagination = this.element.find('.pagination'); // 计时器 this.timer = null; } // 初始化 Banner.prototype.init = function () { var self = this; (function () { // 克隆第一张图片并添加到元素的最后边,设置包裹图片父盒子的宽度 self.wrapper.append(self.firstChild.clone(true)); self.wrapper.css({ width: self.Width * (self.len + 1) }); // 生成对应的分页器按钮 for (var i = 0; i < self.len; i++) { $('').appendTo(self.pagination); } // 动态设置分页器的样式 self.pagination.find('li:first').addClass('active'); var btnWidth = self.pagination.find('li:first').outerWidth(true) * self.len; self.pagination.css({ width: btnWidth, marginLeft: -btnWidth / 2 }) })() // 调用所有绑定的事件 this.nextClick(); this.preClick(); this.btnClick(); this.autoPlay(); this.clearPlay(this.element); } // 切换下一张图片事件 Banner.prototype.nextClick = function () { var self = this; this.next.click(function () { self.moveNext(); }) } // 切换图片,同时也为实现自动播放 Banner.prototype.moveNext = function () { this.n++; // 判断重置时机和重置样式 if (this.n > this.len) { this.n = 1; this.wrapper.css({ marginLeft: 0 }); } this.changeBtn(this.n > 3 ? 0 : this.n); this.wrapper.stop(true, true).animate({ marginLeft: -this.Width * this.n }, this.options.speed) } // 点击切换上一张图片 Banner.prototype.preClick = function () { var self = this; this.prev.click(function () { self.n--; if (self.n < 0) { self.n = self.len - 1; self.wrapper.css({ marginLeft: -(self.len) * self.Width }); } self.changeBtn(self.n < 0 ? self.n = 3 : self.n); self.wrapper.animate({ marginLeft: -self.Width * self.n }, self.options.speed) }) } // 点击分页器切换图片 Banner.prototype.btnClick = function () { var self = this; this.pagination.find('li').click(function () { var index = $(this).index(); self.n = index; self.changeBtn(index); self.wrapper.animate({ marginLeft: -self.Width * index }, self.options.speed) }) } // 动态修改分页器按钮的样式 Banner.prototype.changeBtn = function (index) { this.pagination.find('li').eq(index).addClass('active').siblings().removeClass('active'); } // 自动轮播 Banner.prototype.autoPlay = function () { var self = this; /* 计时器中调用函数是,函数中的this 指向 window, 所以需要使用self.timer = setInterval(function(){ self.moveNext(); },2000); 不能直接使用 self.timer = setInterval(self.moveNext(),2000); 形式 */ self.timer = setInterval(function () { self.moveNext(); }, self.options.interval); } // 清除自动播放 Banner.prototype.clearPlay = function (ele) { var self = this; ele.mouseenter(function () { clearInterval(self.timer) }).mouseleave(function () { // 再次开启自动轮播 self.timer = setInterval(function () { self.moveNext(); }, self.options.interval); }) } // jQuery插件实现 $.fn.myBanner = function (params) { // params 是自定义的配置项 var banner = new Banner(this, params); banner.init(); // 如果需要链式调用 return this; } })(jQuery)
$(function () { $('.mycontainer').myBanner({ // speed:图片切换速度 interval:图片切换的时间间隔 width:图片宽 height:图片高 speed: 500, interval: 3000, width: '324', height: '324' }); })
备注:暂时是整理出来这几种,可以根据自己需要的情况使用,都是简单操作,没有太多比较好看的样式,写法略有不同....如有发现,会放在后面,希望对你们有所帮助