简体   繁体   中英

How to slide images in from the side using JavaScript?

I have a script that displays images sort of like a carousel. The images are placed in LIs and the left positioning is changed based on the width of each slide (all the same). Currently, the old slide just disappears then the new one appears.

I would like to make it so they slide in from the side and was wondering if someone could give me a basic example of how to do this using plain JavaScript (no jQuery.).

For example, I'm using the following code to update the left positioning of the containing UL. How can I make it so it will slide the selected image to the left or to the right (depending upon whether the next or previous button is clicked)

containingUL.style.left = '-' + (slideNumber * slideWidth) + 'px';

Here's a basic element slide function. You can play with the values of steps and timer to get the animation speed and smoothness just right.

function slideTo(el, left) {
    var steps = 25;
    var timer = 25;
    var elLeft = parseInt(el.style.left) || 0;
    var diff = left - elLeft;
    var stepSize = diff / steps;
    console.log(stepSize, ", ", steps);

    function step() {
        elLeft += stepSize;
        el.style.left = elLeft + "px";
        if (--steps) {
            setTimeout(step, timer);
        }
    }
    step();
}

So you could go:

slideTo(containingUL, -slideNumber * slideWidth);

Edit: Forgot to link to the JSFiddle

Edit: To slide to the left, provide a left value less than the current style.left . To slide to the right, provide a value greater than the current style.left . For you it shouldn't matter much. You should be able to plug it into your existing code. I'm guessing your current code either increments or decrements slideNumber and then sets style.left according to the slideNumber. Something like this should work:

if (nextButtonClicked) slideNumber++;
else slideNumber--;
slideTo(containingUL, -slideNumber * slideWidth);

I updated the JSFiddle with a working example of a sliding "gallery", including prev and next buttons. http://jsfiddle.net/gilly3/EuzAK/2/

Simple, non jQuery:

http://sandbox.scriptiny.com/contentslider/slider.html http://www.webmonkey.com/2010/02/make_a_javascript_slideshow/ http://javascript.internet.com/miscellaneous/basic-slideshow.html

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