如何使用javascript每5秒重新加载img? [英] How to reload img every 5 second using javascript?
问题描述
如何使用javascript每5秒重新加载一次img?
How to reload img every 5 second using javascript ?
<img src="screen.jpg" alt="" />
推荐答案
每次要重新加载图像时,都必须像这样更改图像URL:screen.jpg?rand = 123456789,其中123456789是随机生成的数字,每次要重新加载图像时都会重新生成。浏览器会认为它是一个不同的图像,并实际下载它,而不是从缓存中检索它。 Web服务器很可能会忽略并丢弃问号后的所有内容。
Every time you want to reload the image, you must change the image url like so: "screen.jpg?rand=123456789" where "123456789" is a randomly generated number, which is regenerated every time you want to reload the image. The browser will think that it is a different image, and actually download it again, instead of retrieve it from the cache. The web server will most likely ignore and discard everything after the question mark.
要首先重新加载,您必须使用Javascript来获取图像元素并改变来源。我能看到的最简单的选择是给image元素一个 id
属性,如下所示:
To cause the reload in the first place, your would have to use Javascript to get the image element and change the source. The easiest option I can see is to give the image element an id
attribute, like so:
<img src="screen.jpg" id="myImage" />
然后你可以改变图像的来源:
Then you may change the source of the image:
var myImageElement = document.getElementById('myImage');
myImageElement.src = 'screen.jpg?rand=' + Math.random();
要在设定的计时器上执行此操作,请使用顶级Javascript函数 setInterval
:
To do this on a set timer, then use the top-level Javascript function setInterval
:
setInterval(function() {
var myImageElement = document.getElementById('myImage');
myImageElement.src = 'screen.jpg?rand=' + Math.random();
}, 5000);
第二个参数指定5000毫秒,相当于5秒。
The second argument specifies 5000 milliseconds, which equates to 5 seconds.
这篇关于如何使用javascript每5秒重新加载img?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!