【问题标题】:How to define the image source from the content of an HTML page如何从 HTML 页面的内容中定义图像源
【发布时间】:2020-03-27 23:27:23
【问题描述】:

我有一个指向图像 URL 的 html 链接“localurl”(例如,在我的 Sonos 上播放的音乐的当前专辑插图),所以当我在浏览器中提供“localurl”时,它不会直接显示图像,但显示类似“http://image.png”的路径。最后一条路径链接到图像。

我想使用“localurl”在 HTML 文件中显示此图像。我认为它应该看起来像这样:

<!DOCTYPE html>
<html>
<body > 

    <img src=getUrlFromHTML('localurl') >

    <script type="text/javascript">

        function getUrlFromHTML(url)
        {
            ...
        }

    </script>

</body>
</html>

编辑:链接'http://image.png'并不总是相同,我事先不知道,这就是为什么需要使用'localurl'。概念如下:我有一个带有Sonos Binding的openHAB安装,我有一个名为Sonos_CurrentAlbumArtUrl的字符串项,通过openHAB的API,我得到了链接http://openhab.local:8080/rest/items/Sonos_CurrentAlbumArtUrl/state(这是我的'localurl',它指向' http://image.png' 这取决于 Sonos 上播放的音乐(使用 Spotify)。我希望这更清楚一点。

【问题讨论】:

    标签: javascript html image url


    【解决方案1】:

    除非您想引用来自&lt;input type=file 的选定文件,否则您不需要使用javascript。 你可以只写位置。对于可以将图像拖动到浏览器的位置,请从地址栏中复制。

    <img src="file:///C:/Users/nerkn/Documents/cobokin.jpg" 
    

    【讨论】:

      【解决方案2】:

      我花时间学习了一些 javascript,并找到了适合我需要的答案。我在这里分享 HTML-body 的内容,因为我认为它可以帮助其他人。

          <body>
              <img id="SonosAlbumArt">
      
              <script type="text/javascript">
      
                  var link = 'http://openhab.local:8080/rest/items/Sonos_CurrentAlbumArtUrl/state';
                  var img = document.getElementById('SonosAlbumArt');
                  var xhr = new XMLHttpRequest();
                  xhr.addEventListener('readystatechange', function () { refreshAlbumArt()} );
      
                  function sendAlbumArtRequest() {
                      xhr.open('GET', link);
                      xhr.send(null);
                  }
      
                  function refreshAlbumArt() {
                      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                          img.src = xhr.responseText;
                      }
                  }
      
                  setInterval(sendAlbumArtRequest, 1000);
      
               </script>
          </body>
      

      我不太相信setInterval 是最好的方法。我错过了专辑封面更改时触发的事件,以便每秒不发送请求。欢迎任何建议。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-02
        • 1970-01-01
        • 2014-12-13
        • 2013-01-25
        • 2012-07-10
        相关资源
        最近更新 更多