获取<img/>的绝对路径

时间:2010-08-16 19:17:09

标签: javascript url image absolute-path

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

2 个答案:

答案 0 :(得分:19)

只需.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"

答案 1 :(得分: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;
  }