简体   繁体   中英

appendTo not acting as expected

I've got a simple slideshow, that when you click .left , moves and prepends the content. This seems to only affect the last slide:

http://jsfiddle.net/tmyie/4CuLE/4/

$('.left').click(function(){
        $('.box').animate({left: '+=100'}, 100, function(){
        var $last = $('.box').last();
        if ($last.css('left') == '100px') {
            $last.prependTo('.container').before('\n\r');
            $('.box').css('left','0px');
        }
    });
});

However, I've tried to reverse this process with appendTo . This appends to ALL content:

$('.right').click(function(){
        $('.box').animate({left: '-=100'}, 100, function(){
        var $last = $('.box').first();
        if ($last.css('left') == '-100px') {
            $last.appendTo('.container').before('\n\r');
            $('.box').css('left','0px');
        }
    });
});

Would anyone know why appendTo is appending to every item, whereas prependTo is prepending to just one?

I've updated your jsfiddle and now it works. Basically, I've changed your checking method, based on ifs that theoretically should always return true (because you're animating the five objects to the 100px, when you check if the animated property is 100px, it should return true). I don't exactly know why it fails in the first case, but in the second case, when you go right to left, you basically are moving the five elements... but leaving the '\\n\\r' before them, that's why the elements move to the right with each animation.

var $boxes = $('.box');
var max = $boxes.length;
$('.left').click(function(){
    var count = 0;
    $boxes.animate({left: '+=100'}, 100, function(){
        if (++count != max) return; //check whether is the last call to the handler
        var $last = $('.box').last();
        $last.prependTo('.container');
        $('.box').css('left','0px');
    });
});

$('.right').click(function(){
    var count = 0;
    $('.box').animate({left: '-=100'}, 100, function(){
        if (++count != max) return; //check whether is the last call to the handler
        var $last = $('.box').first();
        $last.appendTo('.container');
        $('.box').css('left','0px');
    });
});

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