首先,html部分很是简单,由于图片,按钮等都是在js中动态添加的。css
而后就是css部分html
1 @charset "utf-8"; 2 html,body{ 3 padding:0px; 4 margin:0px; 5 border:0px; 6 } 7 #rq{ 8 position:relative; 9 top:0px; 10 left:0px; 11 width:500px; 12 height:300px; 13 overflow: hidden; 14 15 background-color: #c33; 16 } 17 .img{ 18 width: 500px; 19 height:300px; 20 overflow:hidden; 21 float:left; 22 23 } 24 #rq_hid{ 25 position:absolute; 26 top:0px; 27 left:0px; 28 width:500px; 29 height:300px; 30 overflow: hidden; 31 transition:left 0.5s linear; 32 }
#rq_hid是放置图片的div,这里采用css3中transition方法,向左以线性方式滑动。css3
接下来就是js部分的代码:app
1 var _w=window; 2 var _d=_w.document; 3 var _b=_d.documentElement||_d.body; //这三行是用短字母代写,这是很是好的习惯,尤为在代码量很大的时候,能够简写不少。 4 5 var _rq=_d.getElementById("rq"); 6 var _rqh=_d.getElementById("rq_hid"); 7 8 var imgsrc=new Array(); 9 10 var nowImgId=0; 11 12 var hd; 13 14 imgsrc[0]='1.jpg'; 15 imgsrc[1]='2.jpg'; 16 imgsrc[2]='3.jpg'; 17 imgsrc[3]='4.jpg'; 18 19 var brn_rq=_d.createElement('div'); 20 brn_rq.setAttribute("id","btn_rq"); 21 brn_rq.style.cssText='position:absolute;bottom:10px;right:0px;'; 22 _rq.appendChild(brn_rq); 23 24 btn_rq=_d.getElementById("brn_rq"); 25 26 var imgObj=new Array(); 27 28 for(var i=0;i<imgsrc.length;i++){ 29 var tem_img=_d.createElement("div"); 30 tem_img.className='img'; 31 tem_img.id='img_'+i; 32 tem_img.style.cssText='width:500px;height:300px;'; 33 tem_img.innerHTML='<img src="'+imgsrc[i]+'">'; 34 _rqh.appendChild(tem_img); 35 imgObj[i]=_d.getElementById("img_"+i); 36 var tem_btn=_d.createElement("a"); 37 tem_btn.innerHTML=i+1; 38 tem_btn.setAttribute("id","btn_"+i); 39 tem_btn.style.cssText='color:#fff;background-color:#f00;padding:10px;margin-left:1px;cursor:pointer;'; 40 brn_rq.appendChild(tem_btn); 41 }
这里第一个for循环就是用js动态在html中添加<div><img>标签,以及图片右下角的超连接按钮。函数
1 for(var i=0;i<imgsrc.length;i++){ 2 var tem_btnc=_d.getElementById("btn_"+i); 3 tem_btnc.onmouseover=function(){ 4 var tem_idStr=this.getAttribute("id").split("_"); 5 var id=parseInt(tem_idStr[1]); 6 clearInterval(hd); 7 nowImgId=id; 8 _rqh.style.left=-500*nowImgId+'px'; 9 } 10 tem_btnc.onmouseout=function(){ 11 h(); 12 } 13 14 } 15 16 _rqh.style.width=imgsrc.length*500+'px'; 17 18 for(var i=0;i<imgsrc.length;i++){ 19 imgObj[i].onmouseover=function(){ 20 clearInterval(hd); 21 } 22 imgObj[i].onmouseout=function(){ 23 h(); 24 } 25 }
第二个for循环是对右下角超连接按钮添加功能,鼠标移上去以后,就会调用clearInterval();这个函数,除去图片定时移动的功能。而且还会定位到该按钮对应的图片上,是经过图片的id*图片的宽度实现的。this
第三个for循环是鼠标移到图片上时,也会调用clearInterval();这个函数,使图片定时移动停下来。spa
1 function h(){ 2 hd=setInterval(function(){ 3 if((nowImgId+1)==imgsrc.length){ 4 nowImgId=-1; 5 6 } 7 _rqh.style.left=-500*(nowImgId+1)+'px'; 8 nowImgId++; 9 },1000); 10 } 11 h();
最后,就是函数h(),也就是最后封装成的函数,能够直接引入该js代码,而后经过new h(),来直接使用轮播图。code
最后的效果图,你们能够把他设置的更好看一些htm