Control draggable movement in jQuery

萝らか妹 提交于 2019-12-05 15:17:58

Try using the options inherent in the .draggable() function at http://jqueryui.com/demos/draggable/

basically it says you need to have the snap option set to true like this:

$( ".selector" ).draggable({ snap: true, snapMode:'outer', snapTolerance:40 });

snapMode "...determines which edges of snap elements the draggable will snap to. Ignored if snap is false. Possible values: 'inner', 'outer', 'both'." And snapTolerance is "...The distance in pixels from the snap element edges at which snapping should occur."

Or try using the grid option. This is created to do exactly what you want: "...Grid snaps the dragging helper to a grid, every x and y pixels. Array values: [x, y] Code examples":

Initialize a draggable with the grid option specified.

$( ".selector" ).draggable({ grid: [50, 20] });

Get or set the grid option, after init.

//getter
var grid = $( ".selector" ).draggable( "option", "grid" );
//setter
$( ".selector" ).draggable( "option", "grid", [50, 20] );

Hopefully this helps you.

ok, I've found what I was looking for!

in this link was the piece of code that I needed

the code is this:

//inside drag: function(event, ui)

    var offset = $(this).parent().offset();
    var GRID_SPACING = 10;
    var SELECTION_OFFSET_X = 10;
    var SELECTION_OFFSET_Y = 3;            

    if (parseInt(event.clientX / GRID_SPACING) % 2 == 0)
    {
        var row = Math.floor((event.clientY - offset.top) / GRID_SPACING) + Math.floor(event.clientX / (2 * GRID_SPACING));
        var col = -Math.floor((event.clientY - offset.top) / GRID_SPACING) + Math.floor((event.clientX + GRID_SPACING) / (2 * GRID_SPACING));
    }
    else
    {
        var row = Math.floor((event.clientY + GRID_SPACING / 2 - offset.top) / GRID_SPACING) + Math.floor(event.clientX / (2 * GRID_SPACING));
        var col = -Math.floor((event.clientY + GRID_SPACING / 2 - offset.top) / GRID_SPACING) + Math.floor((event.clientX + GRID_SPACING) / (2 * GRID_SPACING));
    }

    var new_x = row * GRID_SPACING + col * GRID_SPACING - SELECTION_OFFSET_X;
    var new_y = (row * (GRID_SPACING / 2)) - (col * (GRID_SPACING / 2));                     

    if(event.clientX == new_x + GRID_SPACING * 2)
    {
        ui.position.left = new_x;
        new_x = event.clientX;
    }

    if(event.clientY == new_y + GRID_SPACING)
    {
        ui.position.top = new_y;
        new_y = event.clientY;
    }                    

    ui.position.left = new_x;
    ui.position.top = new_y;

I changed some of the constants to adjust to my grid...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!