jQuery Draggable自定义捕捉到网格

时间:2012-06-19 04:30:29

标签: javascript jquery jquery-ui

我在项目中使用jQuery UI Draggable。我有一个复选框,可以在可拖动对象上切换网格(10x10网格)选项。

但是,当网格重新打开时,网格关闭时移动的对象不会与网格关闭时未移动的对象对齐。简而言之,对象位于不排列的单独网格上。

所以我想让对象捕捉到10的增量(当用户拖动它们时,而不仅仅是释放时),这样当网格打开时对象总是会排成一行,但我可以'似乎弄清楚如何在jQuery UI中实现它。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #draggable { width: 100px; height: 70px; background: silver; }
  </style>
  <script>
  $(document).ready(function() {
//  $("#draggable").draggable({ grid: [10, 10] });
$("#draggable").draggable();
$("#draggable").draggable({
   stop: function(event, ui) { 
    var left = ui.position.left;
    var top = ui.position.top;

    left = left - left % 10;
    top = top - top % 10;
$("#draggable").offset({left:left,top:top});
console.log($("#draggable").position());
 }
});
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="draggable">Drag me</div>

</body>

答案 1 :(得分:0)

<!DOCTYPE html>
<html>

<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <style type="text/css">
    #draggable {
      width: 100px;
      height: 100px;
      background: orange;
    }
    
    #container {
      width: 200px;
      height: 200px;
      background: black;
    }
  </style>
  <script>
    $(document).ready(function() {
      $("#draggable").draggable({
        containment: 'parent',
        //grid: [10,10],
        cursor: "move",
        stop: function(event, ui) {
          let startPosition = $(ui.helper).position();
          $(ui.helper).css({
            'left': (Math.round(startPosition.left / 10.0) * 10.0) - 10.0 + 'px',
            'top': (Math.round(startPosition.top / 10.0) * 10.0) - 10.0 + 'px'
          });
          console.log(ui.helper.position());
        }
      });
    });
  </script>
</head>

<body>
  <div id="container">
    <div id="draggable">Drag me</div>
  </div>
</body>