使用Javascript,是否有一种标准方法来获取图像的绝对路径?img.getAttribute("src")
只会返回HTML中声明的src
属性。
使用Javascript,是否有一种标准方法来获取图像的绝对路径?img.getAttribute("src")
只会返回HTML中声明的src
属性。
只需使用.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"
对于相对源路径
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;
}
.src
会将相对路径转换为绝对路径。例如:var a = new Image(); a.src = '/a/../b'; alert(a.src)
会正确地解析。 - Jamie Wongalt
,**src
,... IDL 属性必须反映**相应的同名内容属性。”现在,“反映”在这里的定义是在 https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflect。 - Jason Sparc