使用jQuery.offset()我能够得到接近你想要的结果:http: //jsfiddle.net/G5qBq/3/
它在顶部和左侧都偏离了 10 像素,我不确定为什么。
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass("ui-state-highlight").find("p").html("Dropped!");
var droppableOffset = $('#droppable').offset();
var draggablePos = ui.position;
$('#result').append('<p>#droppable top: ' + droppableOffset.top +
"px left:" + droppableOffset.left +"px");
$('#result').append('<p>#draggable top: ' + draggablePos.top +
"px left:" + draggablePos.left +"px");
$('#result').append('<p>#draggable relative to #droppable top: ' + (draggablePos.top - droppableOffset.top) +
"px left:" + (draggablePos.left - droppableOffset.left) +"px");
}
});
});
更新:修复!
我扔掉了 ui,只为#draggable 使用了一个 jquery 选择器:http: //jsfiddle.net/G5qBq/4/
此代码执行您想要的操作:
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass("ui-state-highlight").find("p").html("Dropped!");
var droppableOffset = $('#droppable').offset();
var draggablePos = $('#draggable').offset();
$('#result').append('<p>#droppable top: ' + droppableOffset.top +
"px left:" + droppableOffset.left +"px");
$('#result').append('<p>#draggable top: ' + draggablePos.top +
"px left:" + draggablePos.left +"px");
$('#result').append('<p>#draggable relative to #droppable top: ' + (draggablePos.top - droppableOffset.top) +
"px left:" + (draggablePos.left - droppableOffset.left) +"px");
}
});
});