Javascript:在 setTimeout 循环中从 DIV 添加和删除图像

Javascript: Append and Remove Image from a DIV in setTimeout loop

我正在尝试使用 JavaScript 将图像加载到 div 中。以下是代码的当前片段。

window.onload=function image_show() {
  var thumbContainer = document.getElementById("art_img");
  var thumbnail = document.createElement("img");
  var img_width = document.getElementById("art_img").offsetWidth;
  var img_height = document.getElementById("art_img").offsetHeight;
  thumbnail.onload=function() { 
    thumbContainer.appendChild(thumbnail);
  }
  thumbnail.src = "http://xyz/bkg.png";
  thumbnail.width = img_width;
  thumbnail.height = img_height;
  setTimeout(image_show, 1000 );
}

appendChild() 方法在超时后继续附加图像(一张在另一张下面)。但我实际上想用相同的图像不断刷新 div 。

图像的来源将在我的网站上以相同的名称更新,我希望脚本在超时后显示新图像。我尝试在 appendChild() 之前插入一个 removeChild() 方法,但没有按预期工作。任何帮助将不胜感激。

问题是浏览器缓存了图片。

尝试将时间戳附加到缩略图的 src 属性:

thumbnail.src = "http://xyz/bkg.png?ts=" + Date.now();

这样,每次 image_show 函数运行时,来源 URL 都会略有不同,每次浏览器都应加载图片。

在再次追加之前清空元素

  thumbnail.onload=function() { 
    thumbContainer.innerHTML = ""; // ADD THIS LINE
    thumbContainer.appendChild(thumbnail);
  }