开发者

jquery photo gallery next-prev button binding problem

开发者 https://www.devze.com 2023-03-07 10:20 出处:网络
I\'m using this photo gallery with this: $(\'.normsize img:gt(0)\').hide(); $(\'.photos a\').click(function(){

I'm using this photo gallery with this:

$('.normsize img:gt(0)').hide();
$('.photos a').click(function(){
    var index = $('.photos a').index(this);
    $('.normsize img:visible').hide();
    $('.normsize img:eq('+index+')').fadeIn();
});

with thumbnails in a div and the normal size pics next to it.

My question is: H开发者_如何学编程ow would I bind the next and previous buttons . Its probably simpler than what I m using already.

Edit: Fixed code output.


You have to store the current image index in a global variable.

var currentIndex = 0;
var lastIndex = $('.normsize img').size() - 1;

function showPic(index) {
    $('.normsize img:visible').hide();
    $('.normsize img:eq('+index+')').fadeIn();
    currentIndex = index;
}

$('.photos a').click(function() {
    showPic($('.photos a').index(this));
});

$('#next').click(function() {
    // If is the last go to first, else go to next
    showPic(currentIndex == lastIndex ? 0 : currentIndex + 1);
});

$('#prev').click(function() {
    // If is the first, go to last, else go to previous
    showPic(currentIndex == 0 ? lastIndex : currentIndex - 1);
});

$('.normsize img').hide(); // Hide all
showPic(0); // Initialize first picture shown
0

精彩评论

暂无评论...
验证码 换一张
取 消