使用 jQuery UI 库在元素拖动时获取正文的坐标



在拖放div 我想获取拖动div 的坐标(坐标应该是左、右和上)我还想使用 ajax 发布这些坐标。示例链接jsfiddle.net/qPw92

<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: "/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>

您所要做的就是为 Draggable 事件添加一个回调:

$('.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/。

试试这个

因此,您必须使用此选项。 position()offset() .

position() 基本上类似于您可以在 CSS 顶部、左侧属性中使用的属性。

offset() 将返回相对于文档的距离。这将考虑边距、填充和边框。

$('#id').offset()

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

最新更新