【问题标题】:Drag and drop divs and store position拖放 div 并存储位置
【发布时间】:2015-12-06 11:29:37
【问题描述】:

我正在尝试制作拖放脚本,但我被卡住了。我想要实现的是:从一侧拖动元素并将它们放在div 中。当我在 div 内移动元素时,我的左侧和顶部位置应该从可放置 div 的边缘计算,而不是整个文档。因此,即使在刷新后,我也可以在确切位置安排和显示拖动的divs。 我的问题是如何获得divs 的位置并进行ajax 调用以将它们存储在数据库中。这是我的代码和 jsfiddle:
html

<div data-id="1" class="ui-widget-content draggable">
  <p>Drag me </p>
</div>
<div data-id="2" class="ui-widget-content draggable">
  <p>Drag me </p>
</div>
<div data-id="3" class="ui-widget-content draggable">
  <p>Drag me </p>
</div>
<div data-id="4" class="ui-widget-content draggable">
  <p>Drag me</p>
</div>
<div  data-id="5" class="ui-widget-content draggable">
  <p>Drag me </p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>
<div id="pos"></div>

js

 $(function() {
    $( ".draggable" ).draggable
    (
    {
        drag: function(){
            var pos=$(this).attr('style');
            $("#pos").html(pos);
            }
    });
    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
          
      }
    });
  });

jsfiddle jsfiddle

编辑 我更新了代码,设法获得了div 的位置,但它并没有从可放置div 的边缘获取它,而是从整个文档中获取位置。

【问题讨论】:

    标签: jquery ajax drag-and-drop draggable jquery-ui-draggable


    【解决方案1】:

    好的,我设法使其正常工作,如果其他人将来需要它,这里是 jsfiddle 和 jquery。 jquery

    $(function() {
        var pos=null;
        var parent=null;
        var current=null;
        $( ".draggable" ).draggable
        (
        {
            drag: function(){
                pos = $(this).offset();
                parent = $( "#droppable" ).offset();
                current = {left: pos.left - parent.left, top: pos.top - parent.top };
                $("#pos").html( current.left + ', ' + current.top );
    
                }
        });
        $( "#droppable" ).droppable({
          drop: function( event, ui ) {
            $( this )
              .addClass( "ui-state-highlight" )
              .find( "p" )
                .html( "Dropped!" );
               $.ajax({
      method: "POST",
      url: "insert.php",
      data: { name: current.left, location: current.top }
    })
    
          }
    
        });
      });
    

    jsfiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多