JavaScript样式和HTML结构
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片滚动</title>
<link rel="stylesheet" href="css/index.css">
<script type="text/javascript">
window.onload=function(){
//获取两个按钮
var prev=document.getElementById('prev');
var next=document.getElementById('next');
var list=document.getElementById('list');
var btn=document.getElementById('buttons').getElementsByTagName('span');
var container=document.getElementById('container');
var index=1;//表示第几个按钮
var timer;
//右箭头
next.onclick=function(){
var oimg=list.getElementsByTagName('img')[0];
list.removeChild(oimg);
list.appendChild(oimg);
//小按钮的移动
if(index==5){
index=1;
}else{
index+=1;
}
for (var i=0;i<btn.length;i++) {
btn[i].className='';
}
btn[index-1].className='on'
}
//左箭头
prev.onclick=function(){
var oimg=list.getElementsByTagName('img')[4];
list.removeChild(oimg);//删除最后一个
list.insertBefore(oimg,list.getElementsByTagName('img')[0])//把最后一张放到第一张
if(index==1){
index=5;
}else{
index-=1;
}
for (var i=0;i<btn.length;i++) {
btn[i].className='';
}
btn[index-1].className='on'
}
//设置自动播放
function play(){
timer=setInterval(function(){
next.onclick()
},2000)
}
play();//调用
function stop(){
clearInterval(timer)
}
container.onmouseover=stop;//鼠标放上去
container.onmouseout=play;//鼠标离开
}
</script>
</head>
<body>
<div id="container">
<div id="list" style="left: 0px;">
<img src="img/111.jpg" alt="1"/>
<img src="img/222.jpg" alt="2"/>
<img src="img/333.jpg" alt="3"/>
<img src="img/444.jpg" alt="4"/>
<img src="img/555.jpg" alt="5"/>
</div>
<div id="buttons">
<span class="on"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<a href="javascript:;" id="prev" class="arrow"><</a>
<a href="javascript:;" id="next" class="arrow">></a>
</div>
</body>
css样式
*{
margin: 0;
padding: 0;
text-decoration: none;
}
body{
padding: 20px;
}
#container{ position: relative;
overflow: hidden;
width: 600px; height: 400px; border: 3px solid #333;
}
#list{ position: absolute;
z-index: 1;
width: 4200px;
height: 400px;
}
#list img{
float: left;
width: 600px;
}
#buttons{
position: absolute;
z-index: 2;
bottom: 20px;
left: 250px;
width: 100px;
height: 10px;
}
#buttons span{float: left;
width: 10px;
height: 10px;
margin-right: 5px;
cursor: pointer;
border: 1px solid #fff;
border-radius: 50%;
background: #333;
}
#buttons .on{
background: orangered;
}
.arrow{font-size: 36px;
font-weight: bold;
line-height: 39px;
position: absolute;
z-index: 2;
top: 180px;
display: none;
width: 40px;
height: 40px;
cursor: pointer;
text-align: center;
color: #fff;
background-color: RGBA(0,0,0,.3);
}
.arrow:hover{
background-color: RGBA(0,0,0,.7);
}
#container:hover .arrow{
display: block;
}
#prev{
left: 20px;
}
#next{
right:20px;
}