Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - Javascript: Clicking thumbnails to switch a larger image. Best method?

I've been looking for a really easy/lightweight way to just be able to click thumbnails to switch the src of a larger image.

I haven't actually tried it out yet. Is this the best solution?

The larger images to be swapped in will have the same width but a different height. Will this cause problems/is there something I need to add for this functionality? Would it be better to do a div with a background-image that swaps and is the height of the largest image?

Also, someone said that it only works once (??)... I'd need it to start out on a certain image, then be able to change to 2-4 other images on thumbnail click.

Thanks for any advice! I'm certainly (obviously) no Javascript writer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be able to switch images as many times as you wish.

The piece of code you reference replaces the image source of #target, with the href of a link within a #thumbs div. It should work fine.

<img id="target" src="images/main.jpg">

<div id="thumbs">
<a href="images/picture1_big.jpg"><img src="images/picture1_small.jpg"></a>
<a href="images/picture2_big.jpg"><img src="images/picture2_small.jpg"></a>
<a href="images/picture3_big.jpg"><img src="images/picture3_small.jpg"></a>
</div>

Now as far as width and height, I am pretty sure there are some cross-browser compatibility issues with how browsers handle a defined width, but an undefined height, when you swap out the images.

In firefox, the following works. Plain old javascript, no jquery:

<html>

   <head>

     <script type="text/javascript">
         function swap(image) {
             document.getElementById("main").src = image.href;
         }
     </script>

   </head>

   <body>

     <img id="main" src="images/main.jpg" width="50">

     <a href="images/picture1_big.jpg" onclick="swap(this); return false;"><img src="images/picture1_small.jpg"></a>
     <a href="images/picture2_big.jpg" onclick="swap(this); return false;"><img src="images/picture2_small.jpg"></a>
     <a href="images/picture3_big.jpg" onclick="swap(this); return false;"><img src="images/picture3_small.jpg"></a>

   </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...