繁体   English   中英

this.src.replace img src用于多个图像

[英]this.src.replace img src for multiple images

将鼠标悬停在图像上时,我想更改图像的来源。

我已经设法完成了一张图片,

<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />"

和:

function colorImage(x){
document.getElementById("image1").src = x.src.replace("grey", "color");
}

我有一打左右的图像-全部有两个版本,灰色和彩色。

现在我想我可以对所有图像单独重复上面的功能,但是必须有一种更简洁的方法。

这是我想的,但是不起作用:

<img id="image1" src="image1-grey.png" onmouseover=colorImage(image1) />"

和:

function colorImage(x){
document.getElementById(x).src = this.src.replace("grey", "color");
}

我想这样一来,我对所有图像都只有一个功能。 但不是。 为什么不?

在此先多谢!

由于您要传递对图像的引用作为参数,因此不需要使用document.getElementById ...已经拥有了!

function colorImage(x){
  x.src = x.src.replace("grey", "color");
}

您可以使用第一种方法继续调用该函数:

<img id="image1" src="image1-grey.png" onmouseover=colorImage(this) />

看起来您的问题出在下面一行的image1

onmouseover=colorImage(image1)

它必须用引号括起来,就像您传递字符串一样(如下所示)

onmouseover=colorImage('image1')

现在,您传递它的方式是发送一个名为image1的JavaScript变量(它将是undefined ),而不是您想要的字符串名称"image1"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM