繁体   English   中英

简单的JS滑块-旋转不起作用

[英]Simple JS Slider - rotation doesn't work

我正在尝试制作一个简单的js幻灯片。 我做了些什么,但是当我单击按钮时,下一张图像只是闪烁而没有停留。 这是我的代码:

var imgArr = new Array();
imgArr=["b1.jpg","b2.jpg","b3.jpg"];
var index = 0;

function myFunction() {
    var Image = document.getElementById("img");
    index++;
    Image.src = imgArr[index];
}

可能是因为您让索引过去了

 var imgArr = new Array(); imgArr[0] = "https://pbs.twimg.com/profile_images/696818834683142145/3SARjDxT.jpg"; imgArr[1] = "http://www.jabaixei.com.br/images/imagens_das_postagens/photoscape_logo_black.png"; imgArr[2] = "http://icon-icons.com/icons2/12/PNG/256/images_nikon_camera_1745.png"; var index = 0; function myFunction() { var Image = document.getElementById("img"); Image.src = imgArr[index]; index++; if (index == 3) index = 0; } 
 <img id="img" src="" " style="width:100px; "/> <button id="btnChange " onclick="myFunction(); ">change</button> 

您必须防止计数器超过数组中的最高索引。 另外,我们可以大大减少您的代码。

 // We can declare and fill the array in one statement: var imgArr = ["http://www.greatgrubclub.com/domains/greatgrubclub.com/local/media/images/medium/4_1_1_apple.jpg", "http://cdn.playbuzz.com/cdn/4bcb7941-ba24-495e-8bc1-6145e8bf1bb5/1be9da1e-92d6-471d-801a-09168c01a5ac.jpg", "http://images.wisegeek.com/red-and-green-barlett-pears.jpg"]; var index = 0; // Just scan the document for the image element once, // not every time the function runs var img = document.getElementById("img"); var btn = document.getElementById("btn"); // You have to set up the click of the button to invoke your function btn.addEventListener("click", myFunction); function myFunction(){ img.src= imgArr[index]; // If the counter is less than one less than the array length, increment it // Otherwise, reset it to zero. if (index < imgArr.length - 1){ index++; } else { index = 0; } } 
 img { width: 50px; } 
 <button id="btn">Next</button><img id="img"> 

暂无
暂无

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

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