如何在jquery中控制draggable的de移动?
我需要做类似于“snap to grid”的事情,其中draggable移动每个“x”和“y”像素
我不能使用“grid:[x,y]”(2D),因为我需要在等距网格(3D)上进行拖动(我稍后会开发网格,我首先需要控制拖动)
例如:当我开始拖动时,拖动不应该移动,当“x”和“y”处于某些条件下时,它必须捕捉到另一个位置
提前感谢!
答案 0 :(得分:1)
尝试使用http://jqueryui.com/demos/draggable/
处的.draggable()函数中固有的选项基本上它表示您需要将snap
选项设置为true
,如下所示:
$( ".selector" ).draggable({ snap: true, snapMode:'outer', snapTolerance:40 });
snapMode“...确定可拖动元素将捕捉到的捕捉元素的哪些边缘。如果捕捉是假的,则忽略。可能的值:'inner','outer','both'。” 而且snapTolerance是“......应该发生捕捉的捕捉元素边缘的距离(以像素为单位)。”
或尝试使用grid
选项。这是为了完全按照你想要的方式创建的:
“...网格将拖动助手捕捉到网格,每个x和y像素。数组值:[x,y]
代码示例“:
使用指定的网格选项初始化一个draggable。
$( ".selector" ).draggable({ grid: [50, 20] });
在init之后获取或设置网格选项。
//getter
var grid = $( ".selector" ).draggable( "option", "grid" );
//setter
$( ".selector" ).draggable( "option", "grid", [50, 20] );
希望这可以帮到你。
答案 1 :(得分:0)
in this link是我需要的代码
代码是这样的:
//内部拖动: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;
我改变了一些常量以适应我的网格......