简体   繁体   中英

advice on how to fix the prev and next buttons of content slider

I'm trying to add in previous and next buttons to my content slider but seem to be having problems, what I would really like to do is move the $slideCtn left or right by the width slideWidth each time the previous or next button is clicked but i'm unsure how to increment each click by the value of slideWidth. I've tried ++ and -- etc but with no results, would anyone be able to show me the best way to do something like this? Also any other advice very welcome!

Or should I create a global index variable that gets set at 0, then as the pagination x's are clicked or the prev/next arrows are clicked update this global variable?

JS Snippet

//Add previous + next arrows
$dirArrows.on('click', function(e){

    var arrDir = $(this).data('dir');

    $slideCtn.css('left', ( arrDir === 'prev' ) ? -(slideWidth) : +(slideWidth));

    e.preventDefault();
});

JS Fiddle http://jsfiddle.net/SG5ad/10/

At the moment, you're telling it to move to an absolute position - either -200px or +200px (never 0px, 400px, 600px, etc).

You'll need to take into account its current position as well as how much you want to adjust it: http://jsfiddle.net/SG5ad/12/

var arrDir = $(this).data('dir')
    iLeft = parseInt( $slideCtn.css('left') );

$slideCtn.css('left', ( arrDir === 'prev' ) ? iLeft - slideWidth : iLeft + slideWidth);

A bug you'll want to fix as well is that the Next/Prev buttons do nothing until you've already jumped to a specific slide with the "x" navigation.


As an entirely separate issue, about 6 months ago I wrote something like this as part of a project at work (it had a few more bells and whistles, but nothing drastically different), and there's one important thing I'd say is worth changing.

In order to go from slide a to slide d at the moment, you animate slides a , b , c and d , which means that
a) 4 slides are animating instead of 1 (plus all their child elements)
b) you have to pass through slides b and c even though they're not relevant

I'd have a look at changing the base position of all your slides to be stacked on top of each other using z-index, then simply animating the top slide off to one side to reveal the one underneath it. It requires a bit of code to track which slides are where ( $.data() may help there) but gives you a much more performant slider at the end of it.

You've gotta do it with .animate()

$dirArrows.on('click', function(e){

    var arrDir = $(this).data('dir');

    if (arrdir == left){
       $slideCtn.animate({
         left: "+=250"
       });
    }
});

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