2012-03-27 2 views
0

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

// 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; 
} 
+0

Вы можете добавить свой HTML также? –

ответ

1

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

+0

близко, но все равно не возвращается в исходное местоположение. Подумайте, что есть проблема с анимированием. –

+0

Это может быть не проблема с анимацией, а вместо CSS позиционирования элементов. Можете ли вы разместить соответствующий CSS? – jeremyharris

+0

Никаких релевантных css в отношении позиционирования не происходит. –

0

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

$(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");      
     }); 
    }); 
}); 
Смежные вопросы