简体   繁体   中英

Image Gallery with right and left buttons

I'm pretty new to jQuery and Javascript!

I've made a image gallery where you can click on small thumbnails below and it selects that picture and shows it in a bigger box.

What I want to add is a button on each side of the bigger image which you click on and it changes to the image to the left or right. Problem is, I just can't figure out how :P

(example: https://imagizer.imageshack.us/v2/757x654q90/34/t4y1.png )

So this is the code for the click on image and it changes to the image you clicked on:

<script type="text/javascript">
    function changePic(img) {
        $("#gallery_img").hide();
        $("#gallery_img").attr ("src", img.src); 
        $("#gallery_img").fadeIn("slow")                
    }
</script>

And this is the HTML part (only the image buttons):

            <div id="gallery_buttons">
                <img id="right" src="pics/right.png"></img>
                <img id="left" src="pics/left.png"></img>
            </div>  

Thanks in advance! :)

Dunno if you're still looking for a solution or not but here is an example what you can do.

HTML

<div id="prev">Prev</div>
<div id="next">Next</div>
<ul>
    <li class="thumb"><img src="http://i.imgur.com/CdxLTkH.png"/></li>
    <li class="thumb"><img src="http://i.imgur.com/N4MgWLu.png"/></li>
    <li class="thumb selected"><img src="http://i.imgur.com/KJyey9r.png"/></li>
    <li class="thumb"><img src="http://i.imgur.com/8nqKP4I.png"/></li>
    <li class="thumb"><img src="http://i.imgur.com/vuvPGHg.png"/></li>
</ul>


<img id="gallery_img" src="#"/>

JQuery

$("li").click(function(){

    var img = $(this).find('img').attr('src');
    $("ul").children().removeClass('selected');
    $(this).addClass('selected');
    $("#gallery_img").attr("src", img); 
});


$('#prev').click(function(){
    var prev = $(".selected").prev();
    var img = prev.find('img').attr('src');
    $("#gallery_img").attr("src", img); 
    $("ul").children().removeClass('selected');
    prev.addClass('selected'); 
});

$('#next').click(function(){
    var next = $(".selected").next();
    var img = next.find('img').attr('src');
    $("#gallery_img").attr("src", img); 
    $("ul").children().removeClass('selected');
    next.addClass('selected'); 
});

Here is the jsfiddle where you can see an example of that code. http://jsfiddle.net/gdSD2/

Obviously it's really rough and can be cleaned up but it works. You also have to remember to account for when the user reaches the end of the list. Add some clause for if there is not next or previous sibling.

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