简体   繁体   中英

getting the absolute path of a <img/>

Using Javascript, is there a standard way to get the absolute path of an image? img.getAttribute("src") only returns the src attribute as it was declared in the HTML.

Just do .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"

For relative source path

  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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM