如何在 JavaScript 中获取图像的 URL? [英] How to get URL of an image in JavaScript?

查看:85
本文介绍了如何在 JavaScript 中获取图像的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Chrome 扩展程序,我正在为页面上的每个图像添加一个 onmouseover 处理程序.当用户将鼠标悬停在图像上时,它的 URL 应该存储在一个变量中.我知道我可以轻松获取图像的 src 属性的值,但我想要完整的 URL.src 属性存储图像在服务器上的路径.例如,当您在 Google Chrome 中右键单击图像时,您将获得复制图像 URL"选项,该选项会将图像的 URL 复制到剪贴板.

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.

有什么办法可以做到这一点吗?谢谢.

Is there any way to achieve this? Thanks.

推荐答案

代替 imageElement.getAttribute("src")$("img.something").attr("src"),它读取原始标记,使用 imageElement.src 属性总是给你完整的 URL.

Instead of imageElement.getAttribute("src") or $("img.something").attr("src"), which reads the original markup, use imageElement.src property which will always give you the full URL.

var imgFullURL = document.querySelector('img.something').src;

或:

var imgFullURL = $('img.something')[0].src;

提取主机名、路径名等 - 使用 URL() 构造函数,适用于现代浏览器或通过创建临时 a 节点使用遗留方法.

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.

这篇关于如何在 JavaScript 中获取图像的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆