jQuery UI Draggable, Snapping to a Grid

前端 未结 2 620
轮回少年
轮回少年 2021-02-04 08:25

I have two containers. A thumbnail container, and a \"page\" container. Both are divs. Thumbnails can be dragged back and forth between the two containers. I have revert on the

2条回答
  •  梦如初夏
    2021-02-04 08:56

    Maybe you could try to round the starting position to the nearest 20 pixels by using the start event on the draggable.

    Something like (untested...):

    $('#draggable').draggable(
        {snap : grid: [20,20]},
        {start : function(event, ui) {
            var startPosition = $(ui.draggable).position(); 
            $(ui.draggable).css({
                'left' : (Math.round(startPosition.left/20)*20)+'px',
                'top' : (Math.round(startPosition.top/20)*20)+'px'});
            }
        }
    );
    

    I'm trying myself to achieve that but I'm cloning the dragged element to another container so that's even more tricky ;-) I still have to figure out how to set the position of the helper in the start event...

    Of course it will only work if the starting position is already absolute (like when dragged).

    As a matter of fact, I've nearly achieved it by applying this method to the stop event and removing the grid property.

    You don't get any visual feedback when moving the object around because there's no grid per se anymore, but when dropping it, it goes to your own grid:

    stop: function(event, ui)   {
        var stopPosition = $(ui.draggable).position();
        $(ui.draggable).css({'left' : (Math.round(stopPosition.left/20)*20)+'px', 'top' : (Math.round(stopPosition.top/20)*20)+'px'});
    }
    

    Here's a working example: http://jsfiddle.net/qNaHE/3/

提交回复
热议问题