在一组图像中只用 javascript 更改 src

Change src with javascript only one in a group of images

本文关键字:javascript 更改 src 图像 一组      更新时间:2023-09-26

我对JavaScript真的很陌生。我刚开始单击图像,该图像也会更改SRC和其他图像。

这是代码:

<a href="#pduno"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pduno.png" width="13" height="11" /></a> 
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a>
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a>

PDUNO.png是"活动"映像,PDDOS.png是"非活动"映像。

让我们想象我有 3 张图片 pduno - pddos - pddos

当我单击 2 个 pddos 中的一个时,它会更改为 pduno

,而 pduno 的那个更改为 pddos。我的意思是,只有一个带有 pduno 的图像,而其余的都是 pddos。

我正在使用它来创建滚动画廊。pduno 用于展示正在展示的画廊。

我会使用jQuery库(因为你需要使用一些不那么简单的函数)

您可以包含它编写此代码(无需下载任何内容):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />

然后,我会这样做:

<a href="#pddos"><img class="pdimg" src="img/pduno.png" width="13" height="11" /></a>
<a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a>
<a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a>

在 HTML 中,我删除了所有脚本,并将它们移到了这里:

<script>
$('.pdimg').click(function(){ //This registers the function with the click event
    $('.pdimg').attr('src', 'img/pddos.png'); //This resets the image to pddos
    $(this).attr('src', 'img/pddos.png'); //This sets the image to uno, 
                             // "this" will be the img that you clicked on.
}
</script>

>document.getElementsByClassName将从文档中选择一个节点列表,而不是单个元素。要更改每个选定元素的 src 属性,您必须遍历列表。

此外,要将所有图像重置为 pddos,然后激活一个图像,您不能将一个图像设置为 pduno,然后重置所有图像。