1
我正在嘗試將可拖動對象的座標保存到x_cord和y_cord變量。這似乎正在工作,但是,當我調用restore()函數時,新對象與原始對象相差很遠。也許我沒有正確理解offset()和position()。jQuery UI保存/恢復丟棄位置
謝謝你看!
節省代碼:
// Set Draggable Options
new_field.draggable({
containment: droppable_page,
stop: function(event, ui) {
x_cord = ui.position.left;
y_cord = ui.position.top;
// This will eventually be saved via AJAX
console.log(x_cord + " " + y_cord);
}
});
恢復代碼:
function restore() {
var draggable = $("#testDrop").draggable();
var droppable = $("#pages_area .page:first").droppable();
var droppableOffset = droppable.offset();
var dx = droppableOffset.left - x_cord;
var dy = droppableOffset.top - y_cord;
draggable.simulate("drag", {
dx: dx,
dy: dy
});
}
全碼:
$(document).ready(function(){
var x_cord;
var y_cord;
$(".page").droppable({
accept: ".droppableShape",
tolerance: 'fit',
drop: function(event,ui){
// Set variables
var new_field = $(ui.helper).clone().removeClass('droppableShape');
var droppable_page = $(this);
var droppableOffset = $(this).offset();
// Check the tool type
switch(new_field.attr('class').split(" ")[0]) {
case "signatureTool":
new_field.data("field-type", "signature");
new_field.css('top', ui.position.top - droppableOffset.top);
new_field.css('left', ui.position.left - droppableOffset.left);
break;
case "initialTool":
new_field.data("field-type", "initial");
new_field.css('top', ui.position.top - droppableOffset.top);
new_field.css('left', ui.position.left - droppableOffset.left);
break;
default:
console.log("Must be our test object!");
}
// Provide Delete Controls
new_field.addClass('field').addClass('btn-delete');
new_field.append('<span class="glyphicon glyphicon-remove btn-delete"><span>');
// Assign this field to a recipient
var recipient_id = $('ul#recipient_list .active').attr("id");
new_field.data("recipient_id", recipient_id);
// Assign this field to a page
var page_id = $(this).attr("id");
new_field.data("page_id", page_id);
// Set Draggable Options
new_field.draggable({
containment: droppable_page,
stop: function(event, ui) {
// I am manually saving these to restore them
x_cord = ui.position.left;
y_cord = ui.position.top;
console.log(x_cord + " " + y_cord);
}
});
// Add to drop area
$(this).append(new_field);
}
});
$('.page').on('click', '.field .btn-delete', function() {
$(this).parent('div').remove();
});
$('#recipient_list').on('click', 'li', function() {
$('#recipient_list li').not(this).removeClass('active');
$(this).addClass('active');
});
}
function restore() {
var draggable = $("#testDrop").draggable();
var droppable = $("#pages_area .page:first").droppable();
var droppableOffset = droppable.offset();
var dx = droppableOffset.left - x_cord;
var dy = droppableOffset.top - y_cord;
draggable.simulate("drag", {
dx: dx,
dy: dy
});
}
請包括一些HTML,以便我們能夠重現您的問題 – devconcept