JQuery Draggable:鼠标释放后是否可以捕捉到网格?

时间:2009-07-31 17:23:22

标签: jquery-ui draggable

基本上,我想使用网格选项将可拖动的div捕捉到30 x 30网格,但我想保持拖动平滑。那么有没有一种方法可以在鼠标释放(或类似的东西)上捕捉网格

3 个答案:

答案 0 :(得分:5)

对@Zed进行更正 这将使用中心来决定放置哪个网格。其中大多数可拖动的网格都是它所在的网格。

stop: function(e, ui) {
    var grid_x = 30;
    var grid_y = 30;
    var elem = $( this );
    var left = parseInt(elem.css('left'));
    var top = parseInt(elem.css('top'));
    var cx = (left % grid_x);
    var cy = (top % grid_y);

    var new_left = (Math.abs(cx)+0.5*grid_x >= grid_x) ? (left - cx + (left/Math.abs(left))*grid_x) : (left - cx);
    var new_top = (Math.abs(cy)+0.5*grid_y >= grid_y) ? (top - cy + (top/Math.abs(top))*grid_y) : (top - cy);

    ui.helper.stop(true).animate({
        left: new_left,
        top: new_top,
        opacity: 1,
    }, 200);
},

答案 1 :(得分:3)

如果您只想对网格进行操作,则可以模拟它:

$("#myobj").draggable({
  ...
  stop: function(event, ui) {
    t = parseInt($(this).css(top);
    l = parseInt($(this).css(left);
    $(this).css(top , t - t % 30);
    $(this).css(left, l - l % 30);
  }
  ...
});

答案 2 :(得分:0)

尝试转换!

我刚刚发现的一个不错的小东西是,如果你给拖动的元素赋予转换的css属性,它会对它捕捉到网格的速度产生影响。



$(function() {
  $(".draggable").draggable({
    containment: 'window',
    grid: [30, 30]
  });
});

.draggable {
  background: #333;
  color: whitesmoke;
  font-family: 'sans-serif', 'arial';
  padding: 5px 12px;
  display: inline-block;
  transition: top 0.05s ease-in-out, left 0.05s ease-in-out
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div class="draggable">Drag Me!</div>
&#13;
&#13;
&#13;