请看下面的jsfiddle: http://jsfiddle.net/G5qBq/
这是我的jQuery代码:
$(function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$('body').append('<br />top: '+ui.position.top);
$('body').append('<br />left: '+ui.position.left);
}
});
});
当我放下掉落区域左上角的可拖动项目时,我希望该位置为0px和0px(我在下降时打印这些值)。
我无法删除相对位置,我不知道如何修复位置。
你能帮我吗?
由于
答案 0 :(得分:0)
使用jQuery.offset()我能够获得您想要的结果:http://jsfiddle.net/G5qBq/3/
上下左右都是10px,我不确定为什么。
$(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");
}
});
});