简体   繁体   中英

jquery slide back and forth or slide round

Please i need help sliding images using jquery back and forth, or just to go round. right now it slides upto the last element and rushes back to the first div and begins again, not beautiful at all,i know i should call back a function to do that but i keep getting mistakes. thanks in advance, this is my jquery code below

$(document).ready(function() {
    var currentPosition = 0;
    var slideWidth = 190;
    var slides = $('.slider_move');
    var numberOfSlides = slides.length;
    var slideShowInterval;
    var speed = 5000;

    slideShowInterval = setInterval(changePosition, speed);                 
    slides.wrapAll('<div id="slidesHolder"></div>')                 
    slides.css({ 'float' : 'left' });                   
    $('#slidesHolder').css('width', slideWidth * numberOfSlides);  

    function changePosition() {
        if(currentPosition == numberOfSlides - 1) {
            currentPosition = 0;
        } else {
            currentPosition++;
        }
        moveSlide();
    }                   
    function moveSlide() {
            $('#slidesHolder')
              .animate({'marginLeft' : slideWidth*(-currentPosition)});
    }
});​

Instead of:

if(currentPosition == numberOfSlides - 1) {
    currentPosition = 0;
} else {
    currentPosition++;
}

You need to move the first slide to the very end (and adjust the position of the container at the same time):

if (currentPosition > 0) {
    $('#slidesHolder').css('marginLeft',0)
        .children().first().appendTo('#slidesHolder');
} else {
    currentPosition += 1;
}

http://jsfiddle.net/mblase75/qatry/

Or, to optimize the whole thing a little more, you can eliminate the currentPosition variable and the moveSlide sub-function, and just use a callback in the .animate method:

function changePosition() {
    $('#slidesHolder').animate({
        'marginLeft': 0-slideWidth
    }, function() {
        $('#slidesHolder').css('marginLeft', 0)
            .children().first().appendTo('#slidesHolder');
    });
}

http://jsfiddle.net/mblase75/8vaCg/

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