重新加载< img>来自同一来源的元素 [英] Reload <img> element from same source

查看:68
本文介绍了重新加载< img>来自同一来源的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在URL http://192.168.1.53/html/cam.jpg(来自Raspberry Pi),并且此图像的变化非常快(来自相机).

I have an image at the URL http://192.168.1.53/html/cam.jpg (from a Raspberry Pi) and this image is changing very fast (it is from a camera).

因此,我想在网站上使用一些JavaScript,例如,每秒将重新加载此图像.

So I want to have some JavaScript on a website that will reload this image every second for example.

我的HTML是:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pi Viewer</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  </head>
  <body>

      <style>
          img,body {
              padding: 0px;
              margin: 0px;
          }
      </style>

      <img id="img" src="http://192.168.1.53/html/cam.jpg">
      <img id="img1" src="http://192.168.1.53/html/cam.jpg">

      <script src="script.js"></script>
  </body>
</html>

还有我的剧本:

function update() {
    window.alert("aa");
    document.getElementById("img").src = "http://192.168.1.53/html/cam.jpg";
    document.getElementById("img1").src = "http://192.168.1.53/html/cam.jpg";
    setTimeout(update, 1000);
}
setTimeout(update, 1000);

警报正在运行,但是图像没有改变:/(我有2幅图像(它们相同))

alert is working, but the image is not changing :/ (I have 2 images (they are the same))

推荐答案

问题是图像src未被更改,因此图像未重新加载.

The problem is that the image src is not altered so the image is not reloaded.

您需要使浏览器确信该映像是新映像.一个很好的技巧是将时间戳记附加到url,以便始终将其视为新的.

You need to convince the browser that the image is new. A good trick is to append a timestamp to the url so that it is always considered new.

function update() {
    var source = 'http://192.168.1.53/html/cam.jpg',
        timestamp = (new Date()).getTime(),
        newUrl = source + '?_=' + timestamp;
    document.getElementById("img").src = newUrl;
    document.getElementById("img1").src =  newUrl;
    setTimeout(update, 1000);
}

这篇关于重新加载&lt; img&gt;来自同一来源的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆