简体   繁体   English

如何为 Javascript 中的幻灯片同步上一个和下一个按钮?

[英]How Do I Make A Previous and next Button synchronized For A Slideshow In Javascript?

I don't get why when I click the forward button everything is ok.我不明白为什么当我单击前进按钮时一切正常。 When I click the previous button everything is ok.当我单击上一个按钮时,一切正常。 but when I mix the two the 1st number is random I think.但是当我将两者混合时,我认为第一个数字是随机的。

 <body> <button id="back"> &lt; </button> <img name="name" width="400px"; height="500px;"> <button id="forward"> ></button> <script> var i = 0; //starting point var images = ["image1.png", "image2.png", "image3.png"]; var forward = document.getElementById("forward"); var back = document.getElementById("back"); function next(){ document.name.src = images[i]; if(i < images.length - 1){ i++; }else i = 0; } function before(){ document.name.src = images[i]; if(i == 0){ i = images.length-1; } else{ i--; } } forward.onclick = function(){ next()}; back.onclick = function(){before()}; </script> </body>

You are assigning the new value before changing i .您在更改i之前分配新值。

With your current logic if you start by pressing > it will show image 0 and set the counter to 1. Then it doesn't matter which button you press, it will show image 1 before changing the value.使用您当前的逻辑,如果您从按 > 开始,它将显示图像 0 并将计数器设置为 1。然后无论您按下哪个按钮,它都会在更改值之前显示图像 1。

You need to assign it afterwards.您需要在之后分配它。

You put document.name.src = images[i];你把document.name.src = images[i]; before calculating index.在计算指数之前。 You probably want that done after .您可能希望. This way the picture reflects yours previous button click and not the the current one.这样,图片会反映您之前的按钮单击,而不是当前的按钮。

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

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