我有五张图片,当鼠标在它上面时,我试图改变它们的来源,问题是当我悬停它时只有第一张图像会改变而另一张图片不会改变,我该怎么解决呢? p>
var img1 = document.querySelector("#image1");
var img2 = document.querySelector("#image2");
var img3 = document.querySelector("#image3");
var img4 = document.querySelector("#image4");
var img5 = document.querySelector("#image5");
var change_images = function(){
if(img1){
img1.src = "images/image1_2.jpg";
}
else if(img2){
img2.src = "images/image2_2.jpg";
}
else if(img3){
img3.src = "images/image3_2.jpg";
}
else if(img4){
img4.src = "images/image4_2.jpg";
}
else if(img5){
img5.src = "images/image5_2.jpg";
}
}
img1.addEventListener("mouseover",change_images);
img2.addEventListener("mouseover",change_images);
img3.addEventListener("mouseover",change_images);
img4.addEventListener("mouseover",change_images);
img5.addEventListener("mouseover",change_images);
答案 0 :(得分:1)
您可能想将悬停的位置提取到函数中
function hoverChange(selector, src){
const img = document.querySelector(selector);
const orig = img.src;
img.addEventListener("mouseover", () => {
img.src = src;
});
img.addEventListener("mouseout", () => {
img.src = orig;
});
}
所以你可以这样做:
window.onload = () => {
hoverChange("#image1", "picture2.png");
//...
};
请注意,您的代码不起作用,因为:
if(img1){
img1
是一个对象,因此 truthy 并且它将始终进入第一个块。您可能希望将事件传递给您的函数:
var change_images = function(event){
然后将目标事件与图像进行比较:
if(img1 === event.target)
答案 1 :(得分:-1)
您可以为函数调用添加一个参数,如下所示:
img1.addEventListener("mouseover",change_images(1));
然后更改你的函数检查以检查你传入的int:
var change_images = function(i) {
if (i === 1) {
img1.src = "images/image1_2.jpg";
}
else if (i === 2) {
img2.src = "images/image2_2.jpg";
// etc.
}
这是一个简单的解决方案,但并未解决您如何获取来源的问题。