如何在 JavaScript 中获取图像的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32828681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get URL of an image in JavaScript?
提问by Bogdan M.
I'm developing a Chrome extension, and I'm adding an onmouseover
handler to each of the images on a page. When the user mouses over an image, it's URL should be stored in a variable. I know I can easily get the value of the src
attribute of the image, but I want the full URL. The src
attribute stores the path of the image on the server. For example, when you right click an image in Google Chrome, you get the "Copy Image URL" option, which copies the image's URL to the clipboard.
我正在开发一个 Chrome 扩展程序,我正在onmouseover
为页面上的每个图像添加一个处理程序。当用户将鼠标悬停在图像上时,它的 URL 应该存储在一个变量中。我知道我可以轻松获取src
图像属性的值,但我想要完整的 URL。该src
属性存储图像在服务器上的路径。例如,当您在 Google Chrome 中右键单击图像时,您会看到“复制图像 URL”选项,该选项会将图像的 URL 复制到剪贴板。
Is there any way to achieve this? Thanks.
有没有办法实现这一目标?谢谢。
回答by wOxxOm
Instead of imageElement.getAttribute("src")
or $("img.something").attr("src")
, which reads the original markup, use imageElement.src
property which will alwaysgive you the full URL.
而不是读取原始标记的imageElement.getAttribute("src")
or $("img.something").attr("src")
,请使用始终为您提供完整 URL 的imageElement.src
属性。
var imgFullURL = document.querySelector('img.something').src;
or:
或者:
var imgFullURL = $('img.something')[0].src;
To extract host name, path name etc. - parse the url with URL()
constructor, which works in modern browsers or use the legacy method via creating a temporary a
node.
提取主机名、路径名等 - 使用URL()
构造函数解析 url ,该构造函数适用于现代浏览器或通过创建临时a
节点使用遗留方法。
回答by amklose
You can use window.location
to get the page you are currently on and the following will give you the URL parts you need:
您可以使用window.location
来获取您当前所在的页面,以下内容将为您提供所需的 URL 部分:
window.location.protocol = "http:"
window.location.host = "stackoverflow.com"
window.location.pathname = "/questions/32828681/how-to-get-url-of-an-image-in-javascript"
So, likely, you will need protocol
, then "//", then host
and finally the image src
.
因此,您可能需要protocol
,然后是“//”,host
最后是图像src
。