javascript this.src.replace img src 用于多张图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15079775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:24:26  来源:igfitidea点击:

this.src.replace img src for multiple images

javascriptreplaceimage

提问by Troublesum

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!

非常感谢!

回答by sachleen

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) />

回答by Troublesum

Looks like your problem is with image1in 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(将是undefined)的 javascript 变量而不是您想要的字符串名称"image1"