开发者

Trying to do a wrap around for an image navigator in JQuery

I am making a simple image navigator using JQuery.

So, for example, if we have 3 images in total, it will look something like this:

Prev 1 2 3 Next

I am using the .hide() function with .click() to implement this.

So every time I click on one navigation option, one image is shown, while the rest are hidden.

I got the "1 2 3" links to work.

I am having problems with the "Prev" and "Next" though.

I have to do a wrap-around for them. So If I am on "1" and I press "Prev", I have to go to "3". Or if I am on "3" and I press "Next", I go to "1".

I wrote the click functions for "Prev" and "Next" like this:

//Write the onClick() event handler for "Prev"
    $('#prev').click(function(){

        ind = ($('.image').index('.image:visible')+1);

        if (ind == 1){
            hideAll(totalImages);
        }
        else{
            hideAll(ind-1);
        }
    });

    //Write the onClick() event hadler for "Next"
    $('#next').click(function(){
        ind = ($('.image').index('.image:visible')+1;

        if (ind == totalImages){
            hideAll(1);
        }
        else{
            hideAll(ind+1);
        }
    });

Note that hideAll(index) is a function which hides all the images except the one specified by "index".

It does not work properly in the following way:

From 1, if I press "Prev", I properly end up at 3. But when I press "Prev" again, all the images go blank. The value of "ind" goes to ZERO.

From 1,开发者_JAVA百科 if I press "Next", I properly end up at 2. But from 2, if I press "Next", I end up at 1 again, rather than going to 3.


You have to to check which image is the first/last in index. This is not the complete solution for your problem but should you give an idea how you can fix it.

Take a look at the previous() and next() function.

// Cache jQuery results
var element = $(this);
var items = element.find(options.slideitem);

// How many items to slide?
var total = items.length;
var count = 0;

// Hide all items but not first item
items.not(':first').hide();

// Calculate next item
function next() {      
    (count == total - 1) ? count = 0 : count++;
    transition(items, count);
    return false
};

// Calculate previous item
function previous() {
    (count == 0) ? count = total - 1 : count--;
    transition(items, count);
    return false
};

// Do transition between two slides
function transition(items, count) {
    if (options.effect == 'show') {
        items.hide().eq(count).show();
    };
    if (options.effect == 'fadeIn') {
        items.css('position', 'absolute');
        items.fadeOut(options.fadespeed).eq(count).fadeIn(options.fadespeed);
    };
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜