HTML和JS
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>輪播圖</title>
<link href="banner.css" rel="stylesheet">
</head>
<body>
<div id='banner'>
<p class="pre" pre='true'><</p>
<p class="fro">></p>
<div id="div1">
</div>
</div>
<script>
var imgs=['1.jpg','2.jpg','3.jpg','4.jpg'];
var count=0;
imgs.forEach(function(val,index){
var img = new Image();
img.src = 'img/' + val;
img.addEventListener('load', oneLoad);
img.addEventListener('error', oneLoad);
})
function oneLoad(){
count++;
if(count == (imgs.length-1)){
init();
}
}
var div = document.getElementById('div1');
function init() {
imgs.forEach(function(val,index){
var img=document.createElement('img');
img.src='img/' + val;
img.style.left = 514 * index + 'px';
div.appendChild(img);
})
count=0;
}
document.getElementById('banner').addEventListener('click',function(e){
var t = e.target;
if(t.innerHTML === '<'){
if(count === 0 ){
count = imgs.length;
}
count --;
//move(div,514*(count+1),514*count)
}else if(t.innerHTML === '>'){
count ++;
if(count === imgs.length ){
count = 0;
}
//move(div,514*(count-1),514*count)
}
div.style.left='-' + (514*count) + 'px';
})
var t;
var pointer=10;
function move(e,start,end){
var num =0;
clearInterval(t);
if(start>end){
t=setInterval(function(){
num++;
if((start + pointer*num)>end)
e.style.left='-' + (start - pointer*num) + 'px';
else
clearInterval(t);
},10)
}else{
t=setInterval(function(){
num++;
if((start + pointer*num)<end)
e.style.left='-' + (start + pointer*num) + 'px';
else
clearInterval(t);
},10)
}
}
</script>
</body>
</html>
CSS
p,span{
padding:0;
margin:0;
}
#banner{
margin:0 auto;
width:512px;
height:384px;
position:relative;
overflow:hidden;
}
#div1{
position:absolute;
left:0px;
}
#div1{
transition: all 2s;
-moz-transition: all 2s; /* Firefox 4 */
-webkit-transition: all 2s; /* Safari 和 Chrome */
-o-transition: all 2s; /* Opera */
}
#div1 img{
position:absolute;
width:512px;
height:384px;
}
#banner p{
position:absolute;
width:20px;
height:384px;
line-height:384px;
color:#fff;
z-index:2;
background-color:grey;
opacity:0.6;
text-align:center;
}
#banner .pre{
left:0px;
top:0px;
}
#banner .fro{
right:0px;
top:0px;
}
注意,记得改图片链接