我需要在一个网页的一个DIV中一个接一个地展示多张图片。两个图像之间应该有一个时间间隔。这是我为此尝试的代码。
$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/cat2.png" />')
wait(1000);
$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog1.png" />')
wait(1000);
$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog2.png" />')
wait(1000);
$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/parrot1.png" />')
wait(1000);
编辑
等待函数在这里
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
但这不起作用,只显示最后一张图片。我怎样才能弄清楚?
最佳答案
您不能在浏览器的行与行之间暂停执行 JavaScript 代码。 (不是以一种有用的方式;alert
和类似的操作。)或者至少,如果您这样做,浏览器的整个 UI(或至少是那个选项卡)会被锁定并且没有页面更新渲染。
相反,安排一系列定时回调来更新您的图像:
[ "D:/Image_Store/Character/Animal/Pet/cat2.png",
"D:/Image_Store/Character/Animal/Pet/dog1.png",
"D:/Image_Store/Character/Animal/Pet/dog2.png",
"D:/Image_Store/Character/Animal/Pet/parrot1.png"
].forEach(function(img, index) {
setTimeout(function() {
$("<img>").attr("src", img).prependTo("#abc");
}, 1000 * index);
});
我们在 0 毫秒后安排第一次更新,在 1000 毫秒后安排第二次更新,在 2000 毫秒后安排第三次更新,等等。
旁注:您的原始代码添加了具有相同 id
值的 多个 img
元素。上面的代码仍然使用多个 img
元素,但没有给它们一个 id
,因为在多个元素上使用相同的 id
是无效。
如果您的目标是使用多个源更新一个单个 img
元素,我们的做法会略有不同:
[ "D:/Image_Store/Character/Animal/Pet/cat2.png",
"D:/Image_Store/Character/Animal/Pet/dog1.png",
"D:/Image_Store/Character/Animal/Pet/dog2.png",
"D:/Image_Store/Character/Animal/Pet/parrot1.png"
].forEach(function(img, index) {
if (index === 0) {
// Create and append the img
$("<img>").attr("id", "theImg").attr("src", img).prependTo("#abc");
} else {
// Update it
setTimeout(function() {
$("#theImg").attr("src", img);
}, 1000 * index);
}
});
关于javascript异步更新一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42187948/