如何获取图片的文件路径(HTML & JS)
How can I get the file path to my picture (HTML & JS)
我正在尝试获取我图片的 SRC 路径文件 link
目前我的代码如下所示
picture.addEventListener("click", (e) => {
console.log(e.target.src)
})
这会打印类似这样的内容
http://127.0.0.1:5500/img/code-mobile.png
而我真正想要的只是看起来像的一点
/img/code-mobile.png
我怎样才能做到这一点?
picture.addEventListener("click", (e) => {
console.log(new URL(e.target.src).pathname)
})
您可以使用 URL
class 为您解析 URL:
picture.addEventListener("click", (e) => {
var url = new URL(e.target.src);
console.log(url.pathname);
})
要获取相对路径而不是绝对路径,请在代码中使用 getAttribute('src') 而不是 src。
您可以从 window.location.host
获取主机字符串,然后在 url.
中用空字符串替换它
类似于:
picture.addEventListener("click", (e) => {
let imageSrc = e.target.src.replace(window.location.href,'');
console.log(imageSrc);
})
我正在尝试获取我图片的 SRC 路径文件 link
目前我的代码如下所示
picture.addEventListener("click", (e) => {
console.log(e.target.src)
})
这会打印类似这样的内容
http://127.0.0.1:5500/img/code-mobile.png
而我真正想要的只是看起来像的一点
/img/code-mobile.png
我怎样才能做到这一点?
picture.addEventListener("click", (e) => {
console.log(new URL(e.target.src).pathname)
})
您可以使用 URL
class 为您解析 URL:
picture.addEventListener("click", (e) => {
var url = new URL(e.target.src);
console.log(url.pathname);
})
要获取相对路径而不是绝对路径,请在代码中使用 getAttribute('src') 而不是 src。
您可以从 window.location.host
获取主机字符串,然后在 url.
类似于:
picture.addEventListener("click", (e) => {
let imageSrc = e.target.src.replace(window.location.href,'');
console.log(imageSrc);
})