简体   繁体   English

JavaScript库-主图像href更改

[英]Javascript Gallery - Main Image href change

I've just been through a tutorial on how to develop a Javascript gallery which changes the 'mainImage' on click when one of the smaller thumbnails is clicked. 我刚刚看过有关如何开发Javascript画廊的教程,当单击较小的缩略图之一时,该画廊会在单击时更改“ mainImage”。

The problem I'm having is that I need the 'mainImage' to link to its own individual page depending on which thumbnail is being presented. 我遇到的问题是,我需要根据显示的缩略图将“ mainImage”链接到其自己的单独页面。

This is my code thus far: 到目前为止,这是我的代码:

<div id="slideshow">
<img class="mainimage" src="Koala.jpg" id="mainimage"/>
</br>
<div id="thumbnailhold" onclick="changeImage(event)">
<img class="imgStyle" src="Chrysanthemum.jpg"/>
<img class="imgStyle" src="Desert.jpg"/>
<img class="imgStyle" src="Hydrangeas.jpg"/>
<img class="imgStyle" src="Jellyfish.jpg"/>
<img class="imgStyle" src="Koala.jpg" />
</div>
</div>

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

You can do it like this: 您可以这样做:

function changeImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG"){
document.getElementById("mainimage").src = targetElement.getAttribute("src");
document.getElementById("mainimagelink").href= 'link'+targetElement.getAttribute("data-link")+'.html';
}

}

You will have to change the HTML like so: 您将必须像这样更改HTML:

<div id="slideshow">
<a id="mainimagelink" href="link1.html">
<img class="mainimage" src="Koala.jpg" id="mainimage"/>
</a>
</br>
<div id="thumbnailhold" onclick="changeImage(event)">
<img class="imgStyle" src="Chrysanthemum.jpg" data-link="1"/>
<img class="imgStyle" src="Desert.jpg" data-link="2"/>
<img class="imgStyle" src="Hydrangeas.jpg" data-link="3"/>
<img class="imgStyle" src="Jellyfish.jpg" data-link="4"/>
<img class="imgStyle" src="Koala.jpg" data-link="5"/>
</div>
</div>

What i did, was add the <a> and ad a data-link attribute to the images, put the page you want to link to in that. 我所做的就是在图像中添加<a>并添加data-link属性,然后将您要链接的页面放入其中。
Currently, it is just using a number, then in the javascript adds link?.html to it: 当前,它只是使用数字,然后在javascript中添加link?.html到它:

document.getElementById("mainimagelink").href= 'link'+targetElement.getAttribute("data-link")+'.html';

Just edit the above line to change the pages. 只需编辑以上行即可更改页面。

JSFiddle Demo JSFiddle演示

EDIT: 编辑:
In response to your comment, change the html to this: 为了回应您的评论,请将html更改为此:

<img class="imgStyle" src="Chrysanthemum.jpg" data-link="Chrysanthemum"/>

And change the line of JavaScript to: 并将JavaScript行更改为:

document.getElementById("mainimagelink").href= targetElement.getAttribute("data-link")+'.html';

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

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