[英]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) />"
And: 和:
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) />"
And: 和:
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?
为什么不?
Thanks a lot in advance! 在此先多谢!
Since you're passing a reference to the image as a parameter, you don't need to use document.getElementById... you already have it! 由于您要传递对图像的引用作为参数,因此不需要使用document.getElementById ...已经拥有了!
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) />
Looks like your problem is with image1
in the line below 看起来您的问题出在下面一行的
image1
上
onmouseover=colorImage(image1)
it needs to be in quotes like you are passing a string (shown below) 它必须用引号括起来,就像您传递字符串一样(如下所示)
onmouseover=colorImage('image1')
The way your passing it now you are sending a javascript variable named image1
(which would be undefined
) instead of the string name you want "image1"
现在,您传递它的方式是发送一个名为
image1
的JavaScript变量(它将是undefined
),而不是您想要的字符串名称"image1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.