简体   繁体   English

如何使此JavaScript幻灯片有效?

[英]How do I get this JavaScript slideshow to work?

I am trying to create an image slideshow. 我正在尝试创建图像幻灯片。 I added the 7 images into the array. 我将7张图片添加到数组中。 The slideshow starts with image0.jpg and when the user clicks on the right arrow, I want the javascript to insert the next image in the array (image1.jpg). 幻灯片以image0.jpg开头,当用户单击向右箭头时,我希望javascript在数组中插入下一个图像(image1.jpg)。 The problem is that the img variable is not going past 1. Can someone help me get this slideshow to work? 问题在于img变量没有超出1。有人可以帮助我使此幻灯片正常工作吗?

HTML 的HTML

    <h1>Swap Image Experiment</h1>
    <div class="slideshow">
        <div id="myImages">
            <img id="test" src="images/image0.jpg">
        </div>
        <div class="arrows"> 
            <div id="left"  onClick="swapPicture(-1)"></div>
            <div id="right" onClick="swapPicture(+1)"></div>
        </div>
    </div>
    <script src="js/script.js"></script>
</body>

JavaScript 的JavaScript

var dImages = new Array();
var numImages = 6;

for(i=0;i<numImages;i++)
{
    dImages[i]=new Image();
    dImages[i].src="images/image"+(i)+".jpg";
}

function swapPicture(target) {
    img = 0;
    image = document.getElementById("test")
    img = img + target;
    console.log(img);
    image.src = "images/image"+(img)+".jpg";
}

You should change img from a local variable to a global variable. 您应该将img从局部变量更改为全局变量。 Now every time when you execute that function, img will be set to 0. So change it to 现在,每次执行该函数时, img都将设置为0。因此将其更改为

var img = 0;
function swapPicture(target) {
    image = document.getElementById("test")
    img = img + target;
    console.log(img);
    image.src = "images/image"+(img)+".jpg";
}

Along with Dacaspex answer, you should remember to loop back to pic 5 (assuming 0-5 for your 6 images) if they go left instead of right. 连同Dacaspex答案一起,如果它们左移而不是右移,您应该记住要回到图5(假设您的6张图像为0-5)。 Also to loop to 0 if they go right when at 5... 如果它们在5点正确,也可以循环到0 ...

var img = 0;
function swapPicture(target) {
    image = document.getElementById("test")
    img = img + target;
    console.log(img);
    if(img < 0)
    {
       img = 5;
    }
    else
    {
       if(img > 5)
       {
          img = 0;
       }
    }
    image.src = "images/image"+(img)+".jpg";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM