英文:
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 = ["{% 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' %}"]
Here is my html image and button
<img src="https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48" id="kp_img">
<button id="kp_button" onclick="kp_animation()">click me</button>
And if this is what my javascript looks like
function kp_animation(){
for(x in data){
setTimout(() => {
document.getElementById("kp_img").src = "kp" + x + ".png";
},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) => {
setTimout(() => {
document.getElementById("kp_img").src = "kp" + x + ".png";
}, 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("#kp_button");
const elKpImg = document.querySelector("#kp_img");
const staticPath = "/static/"; // Or whatever the path to static assets
const data = ["img1.png", "img2.png", "img3.png"]; // populate however you need to
const imagesTotal = data.length;
let imageIndex = 0; // Start from image index 0
let imagesInterval = null;
elKpButton.addEventListener("click", () => {
if (imagesInterval) {
clearInterval(imagesInterval); // Clear interval
imagesInterval = null; // Reset interval ID
} else {
imagesInterval = setInterval(() => {
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 -->
<button id="kp_button">click me</button>
<img src="https://lh3.googleusercontent.com/a/AGNmyxb_rW-rOVKfMwOH50Wy10CcnROIFLMmjfEcvwGU8g=k-s48" id="kp_img">
<!-- 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) => {
setTimeout(() => {
document.getElementById("kp_img").src = "kp" + x + ".png";
//to fullfill promise
resolve(true);
},1000)
})
}
}
kp_animation();
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论