2016-09-27 78 views
2

我在URL http://192.168.1.53/html/cam.jpg(來自Raspberry Pi)上有一個圖像,並且此圖像變化非常快(它來自相機)。重新加載<img>來自同一來源的元素

因此,我想在網站上添加一些JavaScript代碼,例如每秒重新加載一次該圖片。

我的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幅圖像(它們是相同的))

+1

看起來你有2個ID和一個單一的形象而不是2個圖像 –

+0

這裏的問題是該圖像是相同的源每一次,這樣瀏覽器就不會重新加載圖像。您必須手動重新加載圖像才能刷新圖像。 – Aeolingamenfel

+0

我該如何手動重新加載圖像?只有刷新頁面?是不是有其他方法? –

回答

5

問題是圖像src未被更改,因此圖像未重新加載。

您需要說服瀏覽器該圖像是新的。一個很好的訣竅是給URL添加一個時間戳,以便它始終被認爲是新的。

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); 
} 
+0

非常感謝!這個工作;) –