2014-01-06 57 views
-2

當我拖動div並將其放在另一個位置時,我得到該div的座標(例如:左,右,頂部在CSS中)並使用Ajax請求我的控制器將其保存在數據庫中 例如鏈接 jsfiddle.net/qPw92使用jQuery ui庫獲取元素的拖動位置

<html> 
    <head> 
     <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> 
     <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
     <script src="js/jquery-ui.js"></script> 
     <style> 
     .draggable { 
      width: 150px; 
      min-height: 150px; 
      padding: 0.5em; 
      border:1px solid black; 
      overflow-wrap: break-word; 
     } 
     </style> 
     <script> 
     $(function() {    
      $('.draggable').draggable({ 
       var data={ 
        // Get some dives coordinates 
       }; 
       $.ajax({ 
        url: "<?php echo base_url();?>index.php/pages/getinfo/", 
        data: data, 
        type: 'POST', 
        success: function(result){ 
         //alert(result); 
         $("#ajaxResponce").html(result); 
        } 
       }); 
      }); 
     }); 
     </script> 
    </head> 
    <body> 
     <div class="draggable" class="ui-widget-content"> 
      <p>Drag me around</p> 
     </div> 
     <div class="draggable" class="ui-widget-content"> 
      <p>Drag me around</p> 
     </div> 
     <div class="draggable" class="ui-widget-content"> 
      <p>Drag me around</p> 
     </div> 
    </body> 
</html> 
+0

首先,你的代碼有什麼問題?其次,請花時間格式化代碼,以便在您的問題中可讀。 –

回答

1

所有你需要做的就是添加一個回調可拖動事件:

$('.move').draggable({ 
    stop: function(e, ui) { 
     var offset = $(this).offset(), 
      x = offset.left, 
      y = offset.top; 
     $(this).text("Position: (" + x + ", " + y + ")"); 
    } 
}); 

這裏,當拖動對象停止被拖動,它獲取x和y位置並將文本設置爲該位置。你可以在這裏看到一個演示:http://jsfiddle.net/BenedictLewis/vKwFj/

爲了發送,作爲一個AJAX調用,只需編寫一個函數,你可以指定x和y位置:

function sendToDB(x, y){ 
    var data = JSON.stringify({"x": x, "y": y}); 
    $.ajax({ 
     url: "ajax URL", 
     data: data, 
     type: "POST", 
     success:function(result){ 
      // Do something here 
     }); 
    }); 
}); 

然後我們只需撥打我們停止回調函數。另一個演示在這裏:http://jsfiddle.net/BenedictLewis/3Lx7z/

0

試試這個

所以,你必須使用此選項。 position()offset()

position()基本上類似於你可以在CSS top,left properties中使用的東西。

offset()將返回相對於文檔的距離。這考慮了利潤率,填充和邊界。

$('#id').offset()

參考

http://api.jquery.com/position/

+0

主要問題是即使簡單的警報不能在拖動工作我怎麼能發送阿賈克斯請求 任何事件你知道拖曳杆 $('。draggable')。draggable({alert();}); – Adnan

+0

提到這個你的功能必須是這樣的http://stackoverflow.com/questions/9148384/jquery-ui-draggable-does-not-call-custom-function –

+0

http://jsfiddle.net/qPw92/ 我想(「drag」,function(event,ui){ alert('hi') })然後發送給他們ajax請求 – Adnan