【问题标题】:does setting image's url in src attribute enables image to change if it is changed in internet在 src 属性中设置图像的 url 是否可以使图像在 Internet 中更改时更改
【发布时间】:2017-04-17 14:27:23
【问题描述】:

很难形成我的问题标题...我正在编写自己的 windows 侧边栏小工具,我想显示当前的月相,所以我在互联网上搜索了这个,我得到了一个网站显示:

http://www.iceinspace.com.au/moonphase.html

如果我获取图片 url (http://www.iceinspace.com.au/moon/images/phase_150_095.jpg) 并将其设置在图片 src 属性中:

<img id="CurrentMoon" src="http://www.iceinspace.com.au/moon/images/phase_150_095.jpg"></img>

当html文档在javascript中加载时我再次设置:

              function showFlyout(event)
            {
document.getElementById("CurrentMoon").src = "http://www.iceinspace.com.au/moon/images/phase_150_095.jpg";
            }

图片在网上换了会变吗??

【问题讨论】:

    标签: javascript html image src windows-desktop-gadgets


    【解决方案1】:

    您说的是正确的,如果 /moon/images/phase_150_095.jpg 中的图像被新图像替换,即图像文件已更改但图像的 URL 保持不变,您的小部件可以正常工作,但因为它碰巧他们通过更改图像 url 来更改图像(例如,现在它是 phase_150_099.jpg ),因此如果您将 img 的 src 属性设置为固定 URL,它将显示相同的图像。正确的解决方案是:

    1) 假设您的小工具来源与 www.iceinspace.com 不同,请使用 CORS 或 JSONP 向 iceinspace 发出跨域请求 2)创建一个文档对象并通过这样的XPath查找获取图像元素

    function showFlyout(event)
    {
      url = http://www.iceinspace.com.au/moonphase.html;
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      xmlhttp.open('GET', url, true);
      xmlhttp.send(null);
      moonphasedoc = document.implementation.createHTMLDocument("");
      moonphasedoc.open("replace");
      moonphasedoc.write(xmlhttp.responseText);
      moonphasedoc.close(); 
      var element = moonphasedoc.evaluate( '//body/table/tbody/tr/td[3]/p/table/tbody/tr/td/table[1]/tbody/tr/td[1]/img' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; //just copied the Xpath from element inspector :D
      document.getElementById("CurrentMoon").src = element.src;
     }
    

    附:这只有在你有 Access-Control-Allow-Origin: * on the iceinspace 时才有效

    【讨论】:

    • 我认为这是正确的做法,但它不起作用:(,我怎么知道我是否在 iceinspace 上有“Access-Control-Allow-Origin”?
    • @KaramNajjar 您可以在 iceinspace 服务器的响应标头中检查它(您可以在 chrome/firefox 的检查元素中看到那些),但我确信 iceinspace 不会打开 Access- Control-Allow-Origin to all ,在这种情况下,您可以要求网站管理员为您设置。
    【解决方案2】:

    如果服务器(互联网)上的图像发生变化但名称相同且未缓存,那么当您通过 JavaScript 加载图像时,您的图像也会发生变化。

    但是,如果图像被缓存,那么它不会改变(你会看到旧图像)。

    要查看服务器上的最新图像,每次发出请求时,您都需要在 URL 中附加一个唯一的字符串。 例如,

    function showFlyout(event)
    {
        var d = new Date();
        var n = d.getTime();
        document.getElementById("CurrentMoon").src = "http://www.iceinspace.com.au/moon/images/phase_150_095.jpg?v="+n;
    }
    

    【讨论】:

    • 是的,即使图片被缓存了,你的请求也会从服务器获取最新的图片。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多