简体   繁体   中英

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.

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.

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:

<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.
Currently, it is just using a number, then in the javascript adds link?.html to it:

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

Just edit the above line to change the pages.

JSFiddle Demo

EDIT:
In response to your comment, change the html to this:

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

And change the line of JavaScript to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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