jquery animate position - абсолютная или относительная - PullRequest
0 голосов
/ 27 марта 2012

Я хочу сохранить начальное местоположение набора «перетаскиваемых» изображений в качестве атрибутов данных в изображении. Затем, когда нажата кнопка «положить обратно», изображения вернутся к месту происхождения. Проблема в том, что изображения возвращаются в относительное положение. Вместо Top & Left они располагаются в 2XTop и 2XLeft.

    // assign data attributes x,y data attributes       
    $('li img').each(function(index) {
        $(this).data("Left", $(this).parent().position().left)
               .data("Top", $(this).parent().position().top);       
        console.log($(this).data("Top"));
    });

    // button to put images back where they started 
    $("#putBack").bind('click', function() {
        $('li img').each(function(index) {

        console.log($(this).data("Top"));
             $(this).parent().animate(
                     { "left": $(this).data("Left"), 
                             "top": $(this).data("Top")
                     }, "slow");                    
        });

    });

HTML ...

<ul>
<li id='apple'><img src="images/apple.png"/></li>
<li id='bread'><img src="images/bread.png"/></li>
<li id='banana'><img src="images/banana.png"/></li>
<li id='hot_dog'><img src="images/hot_dog.png"/></li>
<ul>

CSS ...

ul{
   width:100px;
   padding:0px;
   list-style:none;
   font-size:20px;
}

Ответы [ 2 ]

1 голос
/ 27 марта 2012

Похоже, вы сохраняете позицию родителя li, а не img. Вот скрипка js, которая запоминает положение изображений и соответственно перемещает их назад: jsfiddle.net / ps7WN

0 голосов
/ 28 марта 2012

Это сделал трюк -

$(document).ready(function(){ 
    $('li').draggable({
            // revert: true,
            cursor: 'pointer',
            opacity: .4,
            containment: 'document'
    });


    // turn on and off dragging 
    $('.toggle').click(function() {
        if ($( "li" ).draggable( "option", "disabled" ) == true){
            $( "li" ).draggable( "option", "disabled", false );             
            $('.toggle').val('Prevent Draggable');
        }
        else{
            $( "li" ).draggable( "option", "disabled", true );              
            $('.toggle').val('Allow Draggable');
        }
    });

    // assign data attributes x,y data attributes       
    $('li img').each(function(index) {
        $(this).data("Left", $(this).parent().offset().left)
               .data("Top", $(this).parent().offset().top);     
        console.log($(this).data("Top"));
    });

    // button to put images back where they started 
    $("#putBack").bind('click', function() {
        $('li img').each(function(index) {                      
             $(this).parent().animate(                   
                 { "left": 0, 
                         "top": 0
                 }, "slow");                    
        });
    });
}); 
...