0

请看下面的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(我在放置时打印这些值)。

我无法删除相对位置,也不知道如何固定位置。

你能帮我吗?

谢谢

4

1 回答 1

0

使用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");
      }
   });
});
于 2013-11-01T01:04:42.503 回答