1. 程式人生 > >JS------------實現簡易幻燈片

JS------------實現簡易幻燈片

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Easy slides</title>
<script> 
var imgArr=new Array("img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg","img/5.jpg");
var index=0;
var cycle_b=false;
//展示上一張圖片
function previous(){
index--;
if(index<0)
index=imgArr.length-1;
document.getElementById("img").src=imgArr[index];
}

//展示下一張圖片
function next(){
index++;
if(index==imgArr.length)
index=0;
document.getElementById("img").src=imgArr[index];

}

//迴圈播放,每三秒播放一張
function cycle(){
if(cycle_b){
cycle_b=false;
window.clearInterval(i);
document.getElementById("body").bgColor="cornflowerblue";
document.getElementById("btn1").type="button"//停止時顯示按鈕
document.getElementById("btn2").type="button"
}else{
cycle_b=true;
i=window.setInterval("next()",1500); //獲取setInterval的返回值 ,用於停止
document.getElementById("body").bgColor="black";
document.getElementById("btn1").type="hidden" //迴圈時隱藏按鈕
document.getElementById("btn2").type="hidden"
}
}

</script>
</head>
<body id="body" align="center" bgcolor="cornflowerblue">
<br/><br/>
<br/><br/>
<img id="img" src="img/1.jpg" width="600" height="500"  onclick="cycle()"/><br/><br/>
<p> 點選圖片自動播放,再次點選取消自動播放</p>
<input id="btn1" type="button" style="width: 100px; "  value="<" onclick="previous()"/>
<input id="btn2" type="button" style="width: 100px;"  value=">" onclick="next()"/>
</body>
</html>