gpt4 book ai didi

javascript - 如何在用户脚本中鼠标悬停时获取图像的 src

转载 作者:行者123 更新时间:2023-11-30 06:44:10 25 4
gpt4 key购买 nike

我是该网站的新手,也是 JavaScript 的新手。我开始编写这个小 UserScript 作为开始。基本上它的作用是,当您将鼠标指针悬停在缩略图上时,如果将该图片放大到弹出窗口。

我使用 Firebug 并确定了包含图像 URL 的正确代码块。

<div id="profPhotos">
<a class="profPhotoLink" href="photo.php?pid=6054657&uid=1291148517">
<img width="163" height="130" src="http://th0.max.ipstatic.net/thumbs/163x130/0e/e9/604x402_1291148517_6054657.jpg">
</a>
<br>
</div>

然后我编写了以下代码来检索变量的 URL。

var thumbURL = document.getElementById("profPhotos").getAttribute("src");

但是当我在 Firebug 控制台中运行那段代码只是为了检查它时,它检索到 null

我是不是做错了什么?非常感谢您的帮助。 :)

最佳答案

您没有显示悬停代码,但这是关键。我假设 <div id="profPhotos">有多张图片,您想对每张图片的悬停进行操作?

此外,这在普通 javascript 中可能会很痛苦,并且 you'll want to use mouseenter versus mouseover , but it's not supported natively in Chrome .

这两个问题的解决方案是 use jQuery .

使用 jQuery,编写类似这样的代码将为您提供图像 src :

$('#profPhotos .profPhotoLink > img').bind (
"mouseenter mouseleave", myImageHover
);

function myImageHover (zEvent) {

if (zEvent.type == 'mouseenter') {
console.log ('Entering src: ', this.src);
}
else {
console.log ('Leaving src: ', this.src);
}
}

使用该代码,您将看到 src记录到控制台的任何图像。

您可以 see this code in action at jsFiddle .


要获取没有鼠标悬停位(或 jQuery)的第一个图像的 src,请使用:

var thumbURL = document.querySelector ('#profPhotos .profPhotoLink > img').src;

关于javascript - 如何在用户脚本中鼠标悬停时获取图像的 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8420456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com