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

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

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

问题

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

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

  1. 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 图片和按钮:

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

如果这是我的 JavaScript 外观:

  1. function kp_animation(){
  2. for(x in data){
  3. setTimout(() => {
  4. document.getElementById("kp_img").src = "kp" + x + ".png";
  5. },1000)
  6. }
  7. }

我试图访问的地址是 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:

  1. 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

  1. &lt;img src=&quot;https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48&quot; id=&quot;kp_img&quot;&gt;
  2. &lt;button id=&quot;kp_button&quot; onclick=&quot;kp_animation()&quot;&gt;click me&lt;/button&gt;
  1. And if this is what my javascript looks like
  2. function kp_animation(){
  3. for(x in data){
  4. setTimout(() =&gt; {
  5. document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
  6. },1000)
  7. }
  8. }

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 将始终引用最后的值,所以自调用函数会有所帮助。

  1. var counter = 0;
  2. for (x in data) {
  3. ((x) => {
  4. setTimeout(() => {
  5. document.getElementById("kp_img").src = "kp" + x + ".png";
  6. }, 1000 * counter++)
  7. })(x)
  8. }

另外,请确保图像的 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.

  1. var counter = 0;
  2. for (x in data) {
  3. ((x) =&gt; {
  4. setTimout(() =&gt; {
  5. document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
  6. }, 1000 * counter++)
  7. })(x)
  8. }

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() 代替。

以下是代码示例:

  1. const elKpButton = document.querySelector("#kp_button");
  2. const elKpImg = document.querySelector("#kp_img");
  3. const staticPath = "/static/"; // 或者是静态资源的路径
  4. const data = ["img1.png", "img2.png", "img3.png"]; // 根据需要填充图像数据
  5. const imagesTotal = data.length;
  6. let imageIndex = 0; // 从图像索引 0 开始
  7. let imagesInterval = null;
  8. elKpButton.addEventListener("click", () => {
  9. if (imagesInterval) {
  10. clearInterval(imagesInterval); // 清除间隔
  11. imagesInterval = null; // 重置间隔 ID
  12. } else {
  13. imagesInterval = setInterval(() => {
  14. elKpImg.src = staticPath + data[imageIndex]; // 设置新图像源
  15. imageIndex += 1; // 递增
  16. imageIndex %= imagesTotal; // 循环回 0
  17. }, 1000);
  18. }
  19. });
  1. img::after { content: attr(src); }
  1. <button id="kp_button">点击我</button>
  2. <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 -->

  1. const elKpButton = document.querySelector(&quot;#kp_button&quot;);
  2. const elKpImg = document.querySelector(&quot;#kp_img&quot;);
  3. const staticPath = &quot;/static/&quot;; // Or whatever the path to static assets
  4. const data = [&quot;img1.png&quot;, &quot;img2.png&quot;, &quot;img3.png&quot;]; // populate however you need to
  5. const imagesTotal = data.length;
  6. let imageIndex = 0; // Start from image index 0
  7. let imagesInterval = null;
  8. elKpButton.addEventListener(&quot;click&quot;, () =&gt; {
  9. if (imagesInterval) {
  10. clearInterval(imagesInterval); // Clear interval
  11. imagesInterval = null; // Reset interval ID
  12. } else {
  13. imagesInterval = setInterval(() =&gt; {
  14. elKpImg.src = staticPath + data[imageIndex]; // set new image source
  15. imageIndex += 1; // increment
  16. imageIndex %= imagesTotal; // loop-back to 0
  17. }, 1000);
  18. }
  19. });

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

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

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

  1. &lt;button id=&quot;kp_button&quot;&gt;click me&lt;/button&gt;
  2. &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:

  1. async function kp_animation() {
  2. for (let x in data) {
  3. await new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. document.getElementById("kp_img").src = "kp" + x + ".png";
  6. //to fullfill promise
  7. resolve(true);
  8. }, 1000);
  9. });
  10. }
  11. }
  12. kp_animation();
英文:

Use async/await for Promise to achieve :

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

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

  1. async function kp_animation(){
  2. for(let x in data){
  3. await new Promise((resolve,reject) =&gt; {
  4. setTimeout(() =&gt; {
  5. document.getElementById(&quot;kp_img&quot;).src = &quot;kp&quot; + x + &quot;.png&quot;;
  6. //to fullfill promise
  7. resolve(true);
  8. },1000)
  9. })
  10. }
  11. }
  12. 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:

确定