效果图
html页面代码
<!--显示的图片-->
<div id="new_lunbo">
<div id="list" style="left:-400px;">
<img src="images/lunbo(3).jpg"/>
<img src="images/lunbo(1).jpg"/>
<img src="images/lunbo(2).jpg"/>
<img src="images/lunbo(3).jpg"/>
<img src="images/lunbo(1).jpg"/>
</div>
<!--显示的图片按钮-->
<div id="list_nav">
<img index="1" class="on" src="images/lunbo(1).jpg"/>
<img index="2" src="images/lunbo(2).jpg"/></span>
<img index="3" src="images/lunbo(3).jpg"/></span>
</div>
</div>
css格式编写
#new_lunbo {
float: left;
height: 300px;
width: 400px;
margin-top: auto;
margin-right: auto;
margin-bottom: auto;
margin-left: 14px;
position: relative;
overflow: hidden;
}
#list {
height: 400px;
width: 2000px;
position: absolute;
z-index: 1;
}
#new_lunbo #list img {
float: left;
}
#list_nav {
position: relative;
margin-top:256px;
z-index: 2;
height: 44px;
width: 400px;
}
#new_lunbo #list_nav img {
cursor: pointer; /*光标呈现为指示链接的指针(一只手)*/
float: left;
margin-top:15px;
margin-left:15px;
height: 21px;
width: 54px;
}
js代码
// JavaScript Document
window.onload = function(){
var lunbo=document.getElementById('new_lunbo');
var list= document.getElementById('list');
var list_nav=document.getElementById('list_nav').getElementsByTagName('img');
var index= 1;
var animated =false;
var timer;
for(var i=0;i<list_nav.length;i++){
list_nav[i].onclick = function(){
var myIndex=parseInt(this.getAttribute('index'));
var offset = -400 * (myIndex-index);
if(!animated){
animate(offset);
}
index = myIndex;
showImgNav();
}
}
function showImgNav(){
for(var i=0;i<list_nav.length;i++){
if(list_nav[i].className=='on'){
list_nav[i].className='';
break;
}
}
list_nav[index-1].className = 'on';
}
//显示内容
function animate(offset){
animeted =true;
var newLeft=parseInt(list.style.left)+offset;
var time =300; //位移总时间
var interval =10; //位移间隔时间
var speed =offset/(time/interval);//每次位移量
function go(){
if((speed< 0 && parseInt(list.style.left)> newLeft) || (speed>0 && parseInt(list.style.left)< newLeft)){
list.style.left=parseInt(list.style.left)+speed +'px';
setTimeout(go,interval);//10毫秒調用一次go
}else{
animated = false;
list.style.left=newLeft+'px';
if(newLeft>-400){
list.style.left = -1200+'px';
}
if(newLeft< -1200){
list.style.left=-400+'px';
}
}
}
go();
}
function play(){
timer = setInterval(function(){
animate(-400);
if(index == 3){index=1;}else{
index+=1;}
showImgNav();
},3000);//一直執行
}
function stop(){
clearInterval(timer);
}
lunbo.onmouseover=stop;//鼠标移动
lunbo.onmouseout=play;
play();
}
总结:我们的轮播图其实修改了一个div中的style=left:-400;的值,动态修改它。和该div中浮动和定位overflow: hidden;