如何在JavaScript中使用数组延迟更改图像的src?

huangapple go评论64阅读模式
英文:

How to chane the src of an image with delays in javascript using an array?

问题

我迄今为止遇到了两个问题,一个是为每张图片设置延迟,另一个是图片的地址有时会与我想要的不同。

我正在一个 Django 模板中进行制作,所以我有以下数组:

var data = ["{% static 'kp1.png' %}", "{% static 'kp2.png' %}", "{% static 'kp3.png' %}", "{% static 'kp4.png' %}", "{% static 'kp5.png' %}", "{% static 'kp6.png' %}", "{% static 'kp7.png' %}", "{% static 'kp8.png' %}", "{% static 'kp9.png' %}", "{% static 'kp10.png' %}", "{% static 'kp11.png' %}", "{% static 'kp12.png' %}", "{% static 'kp13.png' %}", "{% static 'kp14.png' %}", "{% static 'kp15.png' %}", "{% static 'kp16.png' %}", "{% static 'kp17.png' %}", "{% static 'kp18.png' %}", "{% static 'kp19.png' %}", "{% static 'kp20.png' %}", "{% static 'kp21.png' %}", "{% static 'kp22.png' %}", "{% static 'kp23.png' %}", "{% static 'kp24.png' %}"]

这是我的 HTML 图片和按钮:

<img src="https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48" id="kp_img">
<button id="kp_button" onclick="kp_animation()">点击我</button>

如果这是我的 JavaScript 外观:

function kp_animation(){
  for(x in data){
    setTimout(() => {
     document.getElementById("kp_img").src = "kp" + x + ".png";
    },1000)
  }
}

我试图访问的地址是 http://website/static/kpX.png

但如果我在此域 http://website/domain1/domain2 中,它会给我这个:http://website/domain1/domain2/static/kpX.png

另外发生的情况是我得到了第一个延迟,然后它跳到 kp24.png,并且不执行任何其他延迟。

如果有人能帮忙,我将不胜感激。

英文:

I have had two problems so far, setting delays for each of the images and the adresses of the images can sometimes be a different adress than what i wanted.
I am making this on a django template, so I have this as my array:


var data = [&quot;{% static &#39;kp1.png&#39; %}&quot;, &quot;{% static &#39;kp2.png&#39; %}&quot;, &quot;{% static &#39;kp3.png&#39; %}&quot;, &quot;{% static &#39;kp4.png&#39; %}&quot;, &quot;{% static &#39;kp5.png&#39; %}&quot;, &quot;{% static &#39;kp6.png&#39; %}&quot;, &quot;{% static &#39;kp7.png&#39; %}&quot;, &quot;{% static &#39;kp8.png&#39; %}&quot;, &quot;{% static &#39;kp9.png&#39; %}&quot;, &quot;{% static &#39;kp10.png&#39; %}&quot;, &quot;{% static &#39;kp11.png&#39; %}&quot;, &quot;{% static &#39;kp12.png&#39; %}&quot;, &quot;{% static &#39;kp13.png&#39; %}&quot;, &quot;{% static &#39;kp14.png&#39; %}&quot;, &quot;{% static &#39;kp15.png&#39; %}&quot;, &quot;{% static &#39;kp16.png&#39; %}&quot;, &quot;{% static &#39;kp17.png&#39; %}&quot;, &quot;{% static &#39;kp18.png&#39; %}&quot;, &quot;{% static &#39;kp19.png&#39; %}&quot;, &quot;{% static &#39;kp20.png&#39; %}&quot;, &quot;{% static &#39;kp21.png&#39; %}&quot;, &quot;{% static &#39;kp22.png&#39; %}&quot;, &quot;{% static &#39;kp23.png&#39; %}&quot;, &quot;{% static &#39;kp24.png&#39; %}&quot;]

Here is my html image and button

&lt;img src=&quot;https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48&quot; id=&quot;kp_img&quot;&gt;
&lt;button id=&quot;kp_button&quot; onclick=&quot;kp_animation()&quot;&gt;click me&lt;/button&gt;
And if this is what my javascript looks like

function kp_animation(){
  for(x in data){
    setTimout(() =&gt; {
     document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
    },1000)
  }
}

The adress i am trying to acsess is http://website/static/kpX.png

But if i am in this domain http://website/domain1/domain2 then it gives me this: http://website/domain1/domain2/static/kpX.png

What is also happening is i am getting the first delay than it jumps to kp24.png and doesn't do any of the other delays

I would really apreciate it if someone could help

答案1

得分: 0

你需要添加延迟,否则所有的 setTimeout 几乎会同时执行,而且如果不将 x 变成每个 setTimeout 的本地变量,x 将始终引用最后的值,所以自调用函数会有所帮助。

var counter = 0;
for (x in data) {
  ((x) => {
    setTimeout(() => {
      document.getElementById("kp_img").src = "kp" + x + ".png";
    }, 1000 * counter++)
  })(x)
}

另外,请确保图像的 URL 允许跨域加载到不同的站点。

英文:

you need to add the delays else all setTimeout be executed almost at the same time and also without making x a local variable for each setTimeout, x will refer to the last value always so a self invoking function would help.

var counter = 0;
for (x in data) {
  ((x) =&gt; {
    setTimout(() =&gt; {
      document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
    }, 1000 * counter++)
  })(x)
}

Additionally, make sure the image urls allow CORS to be loaded in a different site.

答案2

得分: 0

不确定如何帮助您获取图像路径(具有 Django 初学者的记忆可能会在这里提供帮助),但与您的按钮和interval相关 - ...使用 setInterval 而不是 setTimeout。

另外,要将图像循环回开头,不要忘记取模运算符 % - 它将帮助您将迭代图像索引重置为 0

另外,请不要使用 HTML 内联 on* 事件处理程序。使用 addEventListener() 代替。

以下是代码示例:

const elKpButton = document.querySelector("#kp_button");
const elKpImg = document.querySelector("#kp_img");

const staticPath = "/static/"; // 或者是静态资源的路径
const data = ["img1.png", "img2.png", "img3.png"]; // 根据需要填充图像数据
const imagesTotal = data.length;
let imageIndex = 0; // 从图像索引 0 开始
let imagesInterval = null;

elKpButton.addEventListener("click", () => {
  if (imagesInterval) {
    clearInterval(imagesInterval); // 清除间隔
    imagesInterval = null;         // 重置间隔 ID
  } else {
    imagesInterval = setInterval(() => {
      elKpImg.src = staticPath + data[imageIndex]; // 设置新图像源
      imageIndex += 1;           // 递增
      imageIndex %= imagesTotal; // 循环回 0
    }, 1000);
  }
});
img::after { content: attr(src); }
<button id="kp_button">点击我</button>
<img src="https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48" id="kp_img">

这段代码用于实现图像轮播和按钮控制。希望这对您有所帮助。

英文:

Not sure how to help you with getting the paths to your images (someone with a fresh memory on Django might help here), but related to your button and the interval - ...use setInterval instead of setTimeout.

Also, to loop your images back to the beginning, don't forget about the modulo operator % - it'll help you to reset the iterating images index back to 0

Also, don't use HTML inline on* Event handlers. Use addEventListener() instead.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const elKpButton = document.querySelector(&quot;#kp_button&quot;);
const elKpImg = document.querySelector(&quot;#kp_img&quot;);

const staticPath = &quot;/static/&quot;; // Or whatever the path to static assets
const data = [&quot;img1.png&quot;, &quot;img2.png&quot;, &quot;img3.png&quot;]; // populate however you need to
const imagesTotal = data.length;
let imageIndex = 0; // Start from image index 0
let imagesInterval = null;


elKpButton.addEventListener(&quot;click&quot;, () =&gt; {
  if (imagesInterval) {
    clearInterval(imagesInterval); // Clear interval
    imagesInterval = null;         // Reset interval ID
  } else {
   imagesInterval = setInterval(() =&gt; {
     elKpImg.src = staticPath + data[imageIndex]; // set new image source
     imageIndex += 1;           // increment
     imageIndex %= imagesTotal; // loop-back to 0
   }, 1000);
  }
});

<!-- language: lang-css -->

img::after { content: attr(src); }

<!-- language: lang-html -->

&lt;button id=&quot;kp_button&quot;&gt;click me&lt;/button&gt;
&lt;img src=&quot;https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48&quot; id=&quot;kp_img&quot;&gt;

<!-- end snippet -->

答案3

得分: 0

使用 async/await 来实现 Promise:

async function kp_animation() {
  for (let x in data) {
    await new Promise((resolve, reject) => {
      setTimeout(() => {
        document.getElementById("kp_img").src = "kp" + x + ".png";
        //to fullfill promise
        resolve(true);
      }, 1000);
    });
  }
}

kp_animation();
英文:

Use async/await for Promise to achieve :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

async function kp_animation(){
  for(let x in data){
    await new Promise((resolve,reject) =&gt; {
    setTimeout(() =&gt; {
     document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
     //to fullfill promise
     resolve(true);
    },1000)
    })
  }
}

kp_animation();

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 09:34:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定