Javascript 如何使用javascript每5秒重新加载一次img?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4572193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reload img every 5 second using javascript?
提问by faressoft
How to reload img every 5 second using javascript ?
如何使用javascript每5秒重新加载一次img?
<img src="screen.jpg" alt="" />
回答by AniDev
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.
每次要重新加载图像时,必须像这样更改图像 url:“screen.jpg?rand=123456789” 其中“123456789”是随机生成的数字,每次要重新加载图像时都会重新生成。浏览器会认为它是不同的图像,并实际重新下载它,而不是从缓存中检索它。Web 服务器很可能会忽略并丢弃问号后的所有内容。
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:
首先要导致重新加载,您必须使用 Javascript 来获取图像元素并更改源。我能看到的最简单的选择是给图像元素一个id
属性,如下所示:
<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();
To do this on a set timer, then use the top-level Javascript function setInterval
:
要在设置的计时器上执行此操作,请使用顶级 Javascript 函数setInterval
:
setInterval(function() {
var myImageElement = document.getElementById('myImage');
myImageElement.src = 'screen.jpg?rand=' + Math.random();
}, 5000);
The second argument specifies 5000 milliseconds, which equates to 5 seconds.
第二个参数指定 5000 毫秒,相当于 5 秒。