0

我对javascript相当陌生,但我基本上试图通过图库进行下一次/上一次点击。我已经设法找到教程和位来让图像点击。但是我似乎无法弄清楚如何在第四张(最终)图像之后返回系列的开头。

这就是我到目前为止所拥有的-

<script type="text/javascript">

 var photos=new Array()
 var which=0
 photos[0]='images/image1.jpg'
 photos[1]='images/image2.jpg'
 photos[2]='images/image3.jpg'
 photos[3]='images/image4.jpg'

 function backward(){
    if (which > 0){
        which=which-1
        document.images.photoslider.src=photos[which]
    }
 }

 function forward(){
     if (which<photos.length-1){
        which=which+1
        document.images.photoslider.src=photos[which]
     }
 }

 </script>

 <form>
     <input type="button" value="&lt;&lt;Back" onClick="backward()"> 
     <input type="button" value="Next&gt;&gt;" onClick="forward()">
 </form>

本质上,我希望按钮通过 4 个图像创建一个连续循环。我知道会有一个简单的解决方案,我只是看不到它。任何帮助都会很棒!先感谢您!

4

3 回答 3

2

你可以这样做:

function backward() {
    if (which <= 0) {
        which = photos.length - 1;
    } else {
        which--;
    }
    document.images.photoslider.src=photos[which];
 }

 function forward(){
     which = (which + 1) % photos.length;               //  modulus keeps which within
     document.images.photoslider.src=photos[which];     // the bounds, while incrementing
 }

向后退,如果小于等于 0,则跳到最后一张照片。展望未来,如果 which + 1 == photos.length,模数会将其归零,让您回到起点。

于 2012-08-17T22:18:00.570 回答
0
 function backward(){
    if (which>0){
     which=which-1;
    } else {
     which=photos.length-1;
    }
    document.images.photoslider.src=photos[which];
 }

 function forward(){
    if (which<photos.length-1){
     which=which+1;
    } else {
     which=0;
    }
   document.images.photoslider.src=photos[which];
 }

多田!

于 2012-08-17T22:08:28.930 回答
0
<!DOCTYPE html>
<html>
<body>


<p> click on the button to change the image</p>

     <input type="button" value="&lt;&lt;Back" onClick="backward()"> 

     <img src = "youtube.png" value = "PREVIOUS" id = "prev">


     <input type="button" value="Next&gt;&gt;" onClick="forward()">





<script>

var photos = new Array()
 var i=0
 photos[0]='youtube.png';    //enter the path of the image here
 photos[1]='facebook.png';
 photos[2]='twitter.png';
 photos[3]='sirius_logo_sm.gif';


function backward(){
    if (i>0){
     i=i-1;
    } else {
     i=photos.length-1;
    }
    document.getElementById("prev").src=photos[i];
 }

 function forward()
 {
    if (i<photos.length-1){
     i=i+1;
    } else {
     i=0;
    }
 document.getElementById("prev").src=photos[i]; }


</script>
</body>
</html>
于 2016-08-25T15:35:39.693 回答