开发者

jQuery UI Draggable animation whilst snapping to a grid

jQuery UI Draggable offers a grid option which, when set, will snap your draggable element to a grid. The only problem I'm having with this is I still want it to animate before snapping.

If my grid is [500,500] then there开发者_Go百科 will be no user feedback until the mouse covers a distance of 500px.

Is it possible to do a similar "snap to grid" thing but also animate at the same time?


I presume you mean you want to snap to a grid after the user has finished dragging. In this case, you can make use of the draggable's stop event and calculate the element's offset.

Assume you have a draggable contained within a parent element, starting at offset (0, 0), which is the top-left hand corner. You then apply a regular draggable effect to the element, and on stop you calculate its position and snap it to the nearest "cell".

The code for this would look something like:

$(el).draggable({
  stop: function(e, ui) {
    var elem = ui.helper,
        left = elem.position().left,
        top  = elem.position().top;

    elem.css({
      left: left - (left%10),
      top: top - (top%10)
    });
  }
});

This code will always snap based on the element's top-left pixel co-ordinate, and relies on the element being absolutely positioned and the parent being non-statically positioned (relative, absolute, etc.)

** Edit **

I have created a quick demo - http://jsfiddle.net/LQwMe/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜