4.9.根据轮播图个数修改小圆点数量
src/js/index.js
function Banner() { this.bannerWidth = 798; } Banner.prototype.initBanner = function () { var self = this; this.bannerUL.css({ "width":self.bannerWidth*self.bannerCount }) }; Banner.prototype.initPageControl = function () { var self = this; var pageControl = $(".page-control"); for (var i=0;i<self.bannerCount;i++){ var circle = $("<li></li>"); pageControl.append(circle); if (i === 0){ circle.addClass("active"); } } pageControl.css({"width":self.bannerCount*12+8*2+16*(self.bannerCount-1)}); }; Banner.prototype.run = function () { this.initBanner(); this.initPageControl(); this.loop(); this.listenArrowClick(); };
4.10.小圆点点击事件和自动更新当前选中的小圆点
src/js/index.js
function Banner() { this.pageControl = $(".page-control"); }; Banner.prototype.animate = function () { var self = this; self.bannerUL.animate({"left":-798*self.index},500); // 通过index获取到当前的li标签,添加active样式,兄弟li标签移除active样式 self.pageControl.children('li').eq(self.index).addClass("active").siblings().removeClass("active"); }; Banner.prototype.listenPageControl = function () { var self = this; self.pageControl.children("li").each(function (index,obj) { $(obj).click(function () { self.index = index; self.animate(); }); }); }; Banner.prototype.run = function () { this.listenBannerHover(); };
src/css/scss.css
.header{ z-index: 100; .banner-group{ overflow:hidden; z-index: 0;
4.11.实现自动循环无限轮播
src/js/index.js
function Banner() { this.index = 1; }; Banner.prototype.initBanner = function () { var self = this; //实现无限轮播,原理:123-->>31231,在首尾克隆一张 var firstBanner = self.liList.eq(0).clone(); var lastBanner = self.liList.eq(self.bannerCount-1).clone(); self.bannerUL.append(firstBanner); self.bannerUL.prepend(lastBanner); self.bannerUL.css({ "width":self.bannerWidth*(self.bannerCount+2), "left":-self.bannerWidth, }); }; Banner.prototype.animate = function () { var self = this; self.bannerUL.animate({"left":-798*self.index},500); //小圆点的active var index = self.index; if(index === 0){ index = self.bannerCount-1; }else if(index === self.bannerCount+1){ index = 0; }else{ index = self.index - 1; } // 通过index获取到当前的li标签,添加active样式,兄弟li标签移除active样式 self.pageControl.children('li').eq(index).addClass("active").siblings().removeClass("active"); }; Banner.prototype.loop = function(){ var self = this; this.timer = setInterval(function () { if(self.index >= self.bannerCount+1){ self.bannerUL.css({ "left":-self.bannerWidth, }); self.index = 2; }else{ self.index++; } self.animate(); },2000); };
4.12.左右牵头切换实现循环轮播
src/js/index.js
Banner.prototype.listenArrowClick = function () { var self = this; self.leftArrow.click(function () { if(self.index === 0){ self.bannerUL.css({ "left":-self.bannerCount*self.bannerWidth, }); self.index = self.bannerCount - 1; }else{ self.index --; } self.animate(); }); self.rightArrow.click(function () { if(self.index === self.bannerCount + 1){ self.bannerUL.css({ "left":-self.bannerWidth, }); self.index = 2; }else{ self.index ++; } self.animate(); }); };