繁体   English   中英

如何在javascript中每4秒更改一次图像?

[英]how to change image for every 4 seconds in javascript?

我想更改图像我已经完成代码静止图像根本不显示。 文件未找到错误显示我想每 4 秒更改一次图像我该怎么做? 请帮忙

<html lang="en">
<head>
   
    <title>sliding image</title>
</head>
<body onload="f1()">
    <img id="img1" src=""alt="" width="200px">
    <script>
       let arr=new Array();
        function image()
        {  
              let img2=document.getElementById("img1");
              x=0;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png"
             img2.src=arr[x];
              x=1;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg"
              img2.src=arr[x];
              x=2;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
              img2.src=arr[x];
              x=0;
        }
        function f1()
        {
             window.setInterval(image,4000);
        }
    </script>
</body>
</html>

这些图像的名称为 1.jpg、2.jpg 和 3.jpg,并且与 test.html 和 test.js 文件位于同一文件夹中。 你可以以秒为单位切换超时。

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <script src="test.js" type="text/javascript" defer></script>
</head>
<body>
   <img id="imageSwitcher" src="" alt="">
</body>
</html>
"use strict";

const imageArray = ["1.jpg", "2.jpg", "3.jpg"];
const imageSwitcher = document.getElementById("imageSwitcher");

let timeout = 4;
let i = 0;
setInterval(() => {
   imageSwitcher.src=imageArray[i];
   console.log(i);
   i++;
   if (i >= imageArray.length) {
      i = 0;
   }
}, timeout * 1000);

您必须增加指针并像下面的代码一样重置它。

<script>

    var pointer = 0;

    var imageArray = [
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png",
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg",
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
    ];


    function image()
    {  
      
          let img2 = document.getElementById("img1");
          
          img2.src = imageArray[pointer];

          pointer++;

          // reset the pointer if hit the max
          if (pointer == imageArray.length-1){
            pointer = 0;
          }

    }
    function f1()
    {
         window.setInterval(image,4000);
    }
</script>

暂无
暂无

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

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