Getting jQuery draggable to snap to specific grid

你离开我真会死。 提交于 2019-11-27 12:54:00
Nate

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;
        }
    }  
});

As an alternative to attempting to use the grid option in jQuery UI, I have created my own grid (that you can make visible or invisible using css), then use the snap option and specify the class of each of my grid lines.

To your original jsfiddle, I added the following css:

.gridlines {
display: none;
position:absolute;
background-color:#ccc;
}

and the following javascript:

function createGrid(size) {
  var i,
  sel = $('.drop-target'),
      height = sel.height(),
      width = sel.width(),
      ratioW = Math.floor(width / size),
      ratioH = Math.floor(height / size);

  for (i = 0; i <= ratioW; i++) { // vertical grid lines
    $('<div />').css({
        'top': 0,
        'left': i * size,
        'width': 1,
        'height': height
    })
      .addClass('gridlines')
      .appendTo(sel);
  }

  for (i = 0; i <= ratioH; i++) { // horizontal grid lines
    $('<div />').css({
        'top': i * size,
        'left': 0,
        'width': width,
        'height': 1
    })
      .addClass('gridlines')
      .appendTo(sel);
    }

  $('.gridlines').show();
}

createGrid(20);

Here is the jsFiddle (http://jsfiddle.net/madstop/46sqd/2/)

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