获取<img/>标签的绝对路径

16

使用Javascript,是否有一种标准方法来获取图像的绝对路径img.getAttribute("src")只会返回HTML中声明的src属性。

2个回答

23

只需使用.src即可。

$('img')[0].src = '/images/foo.gif'
"/images/foo.gif"
$('img')[0].src
"http://stackoverflow.com/images/foo.gif"
$('img')[0].getAttribute('src')
"/images/foo.gif"

2
澄清一下——实际上.src会将相对路径转换为绝对路径。例如:var a = new Image(); a.src = '/a/../b'; alert(a.src)会正确地解析。 - Jamie Wong
谢谢,太明显了 :-)) - Pierre
如果不确定,可以查看规范:“alt,**src,... IDL 属性必须反映**相应的同名内容属性。”现在,“反映”在这里的定义是在 https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflect。 - Jason Sparc

0

对于相对源路径

  function getImageURI(imagePath) {
      if (imagePath.indexOf('http') == 0) {
        return imagePath
      }
      var rootPath = window.location.protocol + "//" + window.location.host + "/";
      var path = window.location.pathname;
      if (path.indexOf("/") == 0) {
          path = path.substring(1);
      }
      path = path.split("/", 1);
      if (path != "") {
          rootPath = rootPath + path + "/";
      }
      return rootPath + imagePath;
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接