Stop .animate() when it reaches last div

2019-08-23 12:58发布

So I have a web app where each panel is 480x300 (-20px for status bar) and two navigation buttons to scroll left or right.

Now everything works great, except when you continue scrolling past the max panels displayed, it keeps going.

I was wondering if it is possible to stop the Jquery .animate() after it reaches the last panel.

http://jsfiddle.net/gS33Y/

5条回答
欢心
2楼-- · 2019-08-23 13:35

You can use data-x attributes on the #panel element to count the number of panels, and track which panel is displayed to limit the movement. Also, you should be incrementing the slide margin by 500px (460 width + 20px margin + 20px padding).

Try this:

var $panel = $("#panel")
$panel.data("slideCount", $("#panel li").length).data("currentSlide", 1);

$("nav.back").click(function() {
    if ($panel.data("currentSlide") < $panel.data("slideCount")) {
        $("#panel").animate({
            marginLeft: "-=500px",
        }, 1000);
        $panel.data().currentSlide++;
    }
});

$("nav.forward").click(function(){
    if ($panel.data("currentSlide") > 1) {
        $("#panel").animate({
            marginLeft: "+=500px",
        }, 1000);
        $panel.data().currentSlide--;
    }
});

Example fiddle

查看更多
贼婆χ
3楼-- · 2019-08-23 13:49

You could use a count to track the current display. Something like this http://jsfiddle.net/gS33Y/3/

查看更多
ら.Afraid
4楼-- · 2019-08-23 13:54

Is there anyway to detect when the window width end is near and terminate the marginLeft at the end of slide 5 leaving no white space on the right?

查看更多
在下西门庆
5楼-- · 2019-08-23 13:56

Hiya another demo http://jsfiddle.net/qpHSw/ or http://jsfiddle.net/yEsDQ/ or http://jsfiddle.net/yEsDQ/show

this sample dynamically counts your li in ul and adjust the animate according.

code

   var cur = 1;
var max = $(".scroll-content ul").children("li").length;

$("nav.back").click(function(){

    if (cur+1 > max) return;
    cur++;

    $("#panel").animate({
        marginLeft: "-=500px",
    }, 1000);

});

$("nav.forward").click(function(){
    if (cur-1 < 1) return;
    cur--; 
    $("#panel").animate({
        marginLeft: "+=500px",
    }, 1000);

});​
查看更多
别忘想泡老子
6楼-- · 2019-08-23 13:58

You can restrict the x co-ordinate position to a certain a value if it is last panel.

查看更多
登录 后发表回答