简体   繁体   中英

How do I cap the slider so that my next and prev buttons don't scroll past the content into whitespace?

I've created a fiddle to demonstrate my question. If you continue to hit prev and next the slider bar keeps sliding even past the content.

$('#next').click(function() {
          $('#sliderWrapper').animate({
            marginLeft: "-=200px"
          }, "fast");
       });
$('#prev').click(function() {
      $('#sliderWrapper').animate({
        marginLeft: "+=200px"
      }, "fast");
   });

I assume I need an if statement something like

if (current.width+totalScrolled < slider.width)
{
      $('#sliderWrapper').animate({
        marginLeft: "+=200px"
      }, "fast");
}
else
{
     [soemthing like set.scrollRight = max]
}

and again to keep track of where you are so you don't scroll back too far.

Even a solution that brings you back to the beginning would be a great way to solve this. I just help with logic.

Here are the required if statements:

$('#next').click(function() {
    if($('#sliderWrapper').css("margin-left").replace("px", "")*-1 < $("#imageSlider").width()){
        $('#sliderWrapper').animate({
            marginLeft: "-=200px"
        }, "fast");
    }
});
$('#prev').click(function() {
    if($('#sliderWrapper').css("margin-left").replace("px", "") < 0){
        $('#sliderWrapper').animate({
            marginLeft: "+=200px"
        }, "fast");
    }
});

I also made some improvements to the css. At least, I think they are improvements, feel free to ignore them. The can be found here . Set the width of the slider to anyting, I just set it to 400px for testing.

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