我已经制作了一个带有图像缩略图的滑块,我想在我的页面中使用相同的另一个但是,当我在html中使用相同的代码时,只有第一个正在工作。这就是我想做的this is my page image
<script>
function changeImage(event) {
event = event || window.event;
var targetElement = event.target || event.srcelement;
if (targetElement.tagName == "IMG") {
document.getElementById("mainImage").src = targetElement.getAttribute("src");
}
}
</script>
HTML
<img height="250" width="500" style="border:3px solid grey" src="images/g1.jpg" id="mainImage"></img/>
<br />
<div id="imgstyle" onclick="changeImage(event)">
<image class="imgstyle" src="images/g1.jpg" />
<image class="imgstyle" src="images/g2.jpg" />
<image class="imgstyle" src="images/g3.jpg" />
<image class="imgstyle" src="images/g4.jpg" />
<image class="imgstyle" src="images/g5.jpg" />
</div>
<br />
<img height="250" width="500" style="border:3px solid grey" src="images/g1.jpg" id="mainImage"></img/>
<br />
<div id="imgstyle" onclick="changeImage(event)">
<image class="imgstyle" src="images/g1.jpg" />
<image class="imgstyle" src="images/g2.jpg" />
<image class="imgstyle" src="images/g3.jpg" />
<image class="imgstyle" src="images/g4.jpg" />
<image class="imgstyle" src="images/g5.jpg" />
</div>
<br><br>
CSS
* {
box-sizing: border-box;
}
.imgstyle {
display: block;
float: left;
width: 100px;
}
.imgstyle + .imgstyle {
border-left: 1px solid;
}
答案 0 :(得分:0)
如果您按ID获取元素,则返回第一场比赛 的document.getElementById( “mainImage”); 这就是为什么它只为第一个工作 而是使用
<div id="imgstyle" onclick="changeImage(event, 0)">
<div id="imgstyle" onclick="changeImage(event, 1)"> //for second one
的js
function changeImage(event, a) {
event = event || window.event;
var targetElement = event.target || event.srcelement;
if (targetElement.tagName == "IMG") {
document.getElementsByClassName("mainImage")[a].src = targetElement.getAttribute("src");
}
}
同时将我的主要IMG更改为类
<img height="250" width="500" style="border:3px solid grey" src="images/g1.jpg" class="mainImage"></img/>