点击左右按钮,小圆点切换图片
<div><button><</button><button class="right">></button><h2 id="cont">1/4</h2><img src="./img/1.jpg" alt="" id="pic"><ul><li class="item"></li><li></li><li></li><li></li></ul><h2 id="foot">one</h2></div>
小圆点的特殊样式
.item{background: lightgreen;}
js部分
获取元素
使用数组添加图片及图片信息
var cont = document.getElementById('cont');var foot = document.getElementById('foot');var pic = document.getElementById('pic');var oli = document.getElementsByTagName('li');var btn = document.getElementsByTagName('button');var arr = [{picSrc:'./img/1.jpg',picCont : '1/4',picFoot:'one'},{picSrc:'./img/2.jpg',picCont : '2/4',picFoot:'two'},{picSrc:'./img/3.jpg',picCont : '3/4',picFoot:'three'},{picSrc:'./img/4.jpg',picCont : '4/4',picFoot:'four'}];var count = 0; //记录点击次数
左边按钮
//左边按钮btn[0].onclick = function () {count--;if(count<0){// 图片到达第一张,使图片继续往后,即到达最后一张count = arr.length-1;}for (var j =0; j<oli.length ; j++){//遍历小圆点oli[j].className = ''; //初始化小圆点样式}//将点击的次数作为小圆点的下标,改变小圆点的特殊样式oli[count].className = 'item'; pic.src = arr[count].picSrc;cont.innerHTML = arr[count].picCont;foot.innerHTML = arr[count].picFoot;}
右边按钮
//右边按钮btn[1].onclick = function () {count++;if(count>arr.length-1){//如果点击的次数大于已有的图片数(到达最后一张图片),将count重新归0,即回到第一张count = 0;}for (var j =0; j<oli.length ; j++){//遍历小圆点oli[j].className = ''; //初始化小圆点样式}oli[count].className = 'item';pic.src = arr[count].picSrc;cont.innerHTML = arr[count].picCont;foot.innerHTML = arr[count].picFoot;}
点击小圆点
//点击小圆点for (var i = 0 ;i<oli.length; i++){oli[i].index = i;oli[i].onclick = function () {//关键count = this.index;for (var j =0; j<oli.length ; j++){//遍历小圆点oli[j].className = ''; //初始化小圆点样式}//将点击的次数作为小圆点的下标,改变小圆点的特殊样式oli[count].className = 'item'; pic.src = arr[count].picSrc;cont.innerHTML = arr[count].picCont;foot.innerHTML = arr[count].picFoot;}}
自动轮播
setInterval(function () {console.log(oli.length);count++;if (count > oli.length-1 ) {count = 0;}change();}, 1000)
效果
由于代码重复很多,可以使用函数封装
//封装函数}function change(){for (var j =0; j<oli.length ; j++){oli[j].className = ''; }oli[count].className = 'item'; pic.src = arr[count].picSrc;cont.innerHTML = arr[count].picCont;foot.innerHTML = arr[count].picFoot;}
使用时调用即可