<img src="img/image1.png" id="mainimage">
<p><a href="#" id="pet1">Dog</a></p>
<p><a href="#" id="pet2">Cat</a></p>
我正在尝试使用 JavaScript/jQuery,以便每当用户将鼠标放在 id 为 pet1 和 pet2 的任何链接上时,它都会更改 id 为的图像的图像 src
主图像。
var img = document.getElementById('swap');
document.getElementById('pet1').onmouseover = function(){
// manipulate the image source here.
img.src = img.src.replace(/\.jpg/, '-on.jpg');
}
上面的 JavaScript 是我在这里找到的一个脚本,它似乎具有我正在寻找的功能。唯一的问题是,每当我的鼠标悬停在链接上时,它都不会显示我想要的图像。好的,我正在寻找的问题是如何使带有源的图像(img/pet1.jpg)出现?
任何帮助将不胜感激!
最佳答案
更简单地尝试一下
$(function() {
$("#pet1")
.mouseover(function() {
var src = 'first image path';
$("#mainimage").attr("src", src);
})
.mouseout(function() {
var src2 ='Default image path';
$(this).attr("src", src2;
});
});
与第二张图片类似,甚至为了缩短它,您可以为您想要的每个链接提供一个类,然后通过使用 $(element).each() 函数和 html5 的“data”属性可以用更酷的方式管理它
关于javascript - 鼠标悬停时更改图像源,然后鼠标移开时恢复图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26160352/