Getting jQuery draggable to snap to specific grid

后端 未结 2 1952
春和景丽
春和景丽 2020-12-03 00:14

(NOTE: Some have asked similar questions, but were too specific and yielded no usable answers)

jQuery UI\'s draggable widget has options fo

2条回答
  •  -上瘾入骨i
    2020-12-03 00:32

    I'm going to go ahead and post an answer here, too, though I came here via a followup question you asked.

    You can create your own snap-to-grid functionality very easily inside the drag event on a jQuery UI draggable.

    Basically, you want to check how close the current ui position is at any point that the draggable is being dragged to a grid. That proximity can always be represented as the remainder of the position divided by the grid. If that remainder is less than or equal to the snapTolerance, then just set the position to what it would be without that remainder.

    That was weird to say in prose. In the code it should be more clear:

    Live Demo

    // Custom grid
    $('#box-3').draggable({
        drag: function( event, ui ) {
            var snapTolerance = $(this).draggable('option', 'snapTolerance');
            var topRemainder = ui.position.top % 20;
            var leftRemainder = ui.position.left % 20;
    
            if (topRemainder <= snapTolerance) {
                ui.position.top = ui.position.top - topRemainder;
            }
    
            if (leftRemainder <= snapTolerance) {
                ui.position.left = ui.position.left - leftRemainder;
            }
        }  
    });
    

提交回复
热议问题