2016-12-02 64 views
2

我知道这个问题经常被问到,但我不能复制一个代码。 我希望图像在一段时间后改变。我想我犯了很多错误的编码错误。下面是我的代码。更改定时器上的图像,

预先感谢帮助,

碧玉

<!DOCTYPE html> 
    <html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>test</title> 
     <link rel="stylesheet" type="text/css" href="/css/styles.css"> 
    </head> 
     <body> 

     <img id="image" src="foto1.jpg"> 







      <script type = "text/javascript"> 

       var image=document.getElementById("image"); 
       function volgendefoto() { 

       if (images==0){ 
        image.src="foto2"; 

       } 

        if (images==1){ 
         image.src="foto2"; 

        } 
         if (images==3){ 
          image.src="foto1"; 

         } 
      } 

      function timer(){ 

       setInterval(volgendefoto, 3000); 
          } 

      var images= [], x = -1; 
       image[0]="foto1.jpg"; 
       image[1]="foto2.jpg"; 
       image[2]="foto3.jpg"; 



      </script> 
     </body> 
    </html> 
+0

“无法复制的代码”?听起来像一个学校的任务。回到我的日子里,我们知道如何复制粘贴并更改变量名称;) – xShirase

+0

是的,它是为了学校。它太明显,如果我复制它,他们知道我的编码行为和常见错误:) –

+0

@xShirase,哈哈ikr –

回答

3
<!DOCTYPE html> 
    <html lang="en"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>test</title> 
     <link rel="stylesheet" type="text/css" href="/css/styles.css"> 
    </head> 
     <body> 

     <img id="image" src="foto1.jpg"> 





     <script type = "text/javascript"> 

      var image=document.getElementById("image"); 
      var currentPos = 0; 
      var images = ["foto1.jpg","foto2.jpg","foto3.jpg"] 

      function volgendefoto() { 
       if (++currentPos >= images.length) currentPos = 0; 
       image.src = images[currentPos]; 
      } 

      setInterval(volgendefoto, 3000); 

     </script> 





     </body> 
    </html> 
+0

感谢您的快速回答!有用! –

+0

标记它就像“正确的答案”:) – ixpl0

+0

是的,我做了,我不得不再等3分钟 –

2

你没有创建间隔,从不执行定时器。这里是一个将循环您的图片,假设你的第一个图像的图像是一个预加载(如:images[0] === image.src在页面加载):

const image=document.getElementById("image"); 
    let images= ["foto1.jpg","foto2.jpg","foto3.jpg"], i = 0; 

    function volgendefoto() { 
     i<images.length?i+=1:i=0; 
     image.src=images[i]; 
    } 
    setInterval(volgendefoto, 3000); 
+0

感谢您的快速答案!我已经接受了上面的答案,因为我可以理解这个答案!目前你的代码对我来说有点复杂。 –

+1

const并让ES6声明,你的老师应该强迫你使用它们:p和三元表达式,它只是一个if。 – xShirase

+1

我会问他的!谢谢! –