对齐 draggable 到 DOM 元素的内部或外部边界。使用 snap
、snapMode
(inner, outer, both)和 snapTolerance
(当调用对齐时,draggable 与元素之间的距离,以像素为单位)选项。
或者对齐 draggable 到网格。通过 grid
选项设置网格单元的尺寸(以像素为单位的高度或宽度)。
默认(snap: true),对齐到所有其他的 draggable 元素
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI 拖动(Draggable) - 对齐到元素或网格</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
<style>
.draggable { width: 90px; height: 80px; padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em; }
.ui-widget-header p, .ui-widget-content p { margin: 0; }
#snaptarget { height: 140px; }
</style>
<script>
$(function() {
$( "#draggable" ).draggable({ snap: true });
$( "#draggable2" ).draggable({ snap: ".ui-widget-header" });
$( "#draggable3" ).draggable({ snap: ".ui-widget-header", snapMode: "outer" });
$( "#draggable4" ).draggable({ grid: [ 20, 20 ] });
$( "#draggable5" ).draggable({ grid: [ 80, 80 ] });
});
</script>
</head>
<body>
<div id="snaptarget" class="ui-widget-header">
<p>我是对齐目标</p>
</div>
<br style="clear:both">
<div id="draggable" class="draggable ui-widget-content">
<p>默认(snap: true),对齐到所有其他的 draggable 元素</p>
</div>
<div id="draggable2" class="draggable ui-widget-content">
<p>我只对齐到大盒子</p>
</div>
<div id="draggable3" class="draggable ui-widget-content">
<p>我只对齐到大盒子的外边缘</p>
</div>
<div id="draggable4" class="draggable ui-widget-content">
<p>我对齐到一个 20 x 20 网格</p>
</div>
<div id="draggable5" class="draggable ui-widget-content">
<p>我对齐到一个 80 x 80 网格</p>
</div>
</body>
</html>