this.src.replace img src用于多个图像 [英] this.src.replace img src for multiple images
问题描述
我想在悬停在图像上时更改图像的来源。
I want to change the source of an image when hovering over it.
我已经设法为一张图片做了这件事,
I've managed to do it for one image, by
<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />"
并且:
function colorImage(x){
document.getElementById("image1").src = x.src.replace("grey", "color");
}
我有十几张图片 - 全部有两个版本,灰色和彩色。
I have a dozen or so images - all in two versions, grey and color.
现在我想我可以单独为所有图像重复上面的功能,但必须有一个更清洁的方式。
Now I guess I could repeat the function above for all the images individually, but there must be a cleaner way.
这是我想的,但它不起作用:
This is what I figured, but it doesn't work:
<img id="image1" src="image1-grey.png" onmouseover=colorImage(image1) />"
并且:
function colorImage(x){
document.getElementById(x).src = this.src.replace("grey", "color");
}
这样,我想,我只有一个函数可用于所有图片。但不是。为什么不呢?
This way, I thought, I'd only have one function for all the images. But no. Why not?
提前多多谢谢!
推荐答案
你传递对图像的引用作为参数,你不需要使用document.getElementById ......你已经拥有它了!
Since you're passing a reference to the image as a parameter, you don't need to use document.getElementById... you already have it!
function colorImage(x){
x.src = x.src.replace("grey", "color");
}
您可以继续使用第一种方式调用该函数:
You can continue to call the function using your first way:
<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />
这篇关于this.src.replace img src用于多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!