使用上一个和下一个按钮制作Img幻灯片

时间:2015-05-30 16:53:25

标签: javascript arrays image slideshow

如何制作它以便当我单击Next时它将转到下一个数组图像,当我单击Previous时它将转到上一个数组图像。我正在尝试制作一个有两个按钮的图像幻灯片。一个转到下一个图片,一个转到上一个图片

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">



<script>
    var images = new Array(7);  
    images[0] = "Images/lab1.jpeg";
    images[1] = "Images/lab2.jpeg";
    images[2] = "Images/lab3.jpeg";
    images[3] = "Images/lab4.jpeg";
    images[4] = "Images/lab5.jpeg";
    images[5] = "Images/lab6.jpeg";
    images[6] = "Images/lab7.jpeg";
    images[7] = "Images/lab8.jpeg";
    var num_img = 7;
    var cur_img = 1;

  function  goback() {

    if(cur_img>0)
   {

    cur_img = cur_img - 1;
   }else{
    alert("This is the first image");
   }


}

function gofwd(){

    if(cur_img < num_img){

    cur_img = cur_img + 1;
   }else{
      alert("This is the last image");
      }


}


</script>


</script>




</head>
<body>

<div style="border: solid 12px blue; width: 500px; height: 500px;">
<img src="Images/lab1.jpeg" alt="lab1" height="500" width="500">
</div><br>
<input type="button" value="PREVIOUS" id="prev" name="prev" style="color:blue" onclick="goback();" >

<input type="button" value="NEXT" id="next" name="next" style="color:blue" onclick="gofwd();" >





</body>
</html>

1 个答案:

答案 0 :(得分:0)

首先

switch是javascript中的关键字,因此您无法将其用作标识符。所以重命名你的图像数组。在HTML中为您的图片提供ID,然后尝试下面的代码。

<script>
    var images = new Array(7);  
    images[0] = "Images/lab1.jpeg";
    images[1] = "Images/lab2.jpeg";
    images[2] = "Images/lab3.jpeg";
    images[3] = "Images/lab4.jpeg";
    images[4] = "Images/lab5.jpeg";
    images[5] = "Images/lab6.jpeg";
    images[6] = "Images/lab7.jpeg";

    var numimg = 7;
    var curimg = 1;

  function  goback() {
    var im=document.getElementById("image");
    if(curimg>0)
   {
    im.src = images[curimg-1];
    curimg = curimg - 1;
   }else{
    alert("This is the first image");
   }


}

function gofwd(){
var im=document.getElementById("image");
    if(curimg < numimg){
    im.src = images[curimg+1];
    curimg = curimg + 1;
   }else{
      alert("This is the last image");
      }


}


</script>

HTMl就像

<div style="border: solid 12px blue; width: 500px; height: 500px;">
<img src="Images/lab1.jpg" alt="lab1" height="500" width="500" id="image" />
</div><br>
<input type="button" value="PREVIOUS" id="prev" name="prev" onclick="goback();" >

<input type="button" value="NEXT" id="next" name="next" onclick="gofwd();" >