3

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

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

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

4

2 回答 2

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>
于 2012-06-19T04:44:23.967 回答
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>

于 2018-10-22T23:12:14.027 回答