这个问题之前已经被问过好几次了,但我还没有看到任何答案。我本来想尝试一下。
我在多个项目上使用 jQuery UI 可拖动(和可放置)功能。拖动项目时,它们永远不会对齐到同一网格线,因此这使得排列项目毫无意义。
我尝试布置一千个 <div class="grid-cell">
但是当在几个可放置区域和 CSS 动画上复制时,这会导致一些明显的性能问题。
以下是未排列到同一网格的项目的示例:http://jsfiddle.net/K3zzY/
以下是一些类似的问题: jQuery Draggable Custom Snap to Grid jQuery UI Draggable, Snapping to a Grid https://stackoverflow.com/questions/17353256/jquery-ui-draggable-to-fixed-grid
感谢您的任何建议。
我还尝试在:drag 上操纵可拖动的位置,但它似乎不起作用,因为元素似乎从未重新定位。
我的方法 使用此处的代码建议:Draggable square/rectangle that snaps to grid in JQuery/Javascript
我的代码为:
drag:function(e, ui){
if(snapToGrid === true){
ui.position.left = Math.floor((e.pageX - f._wrapper.offset().left) / snapToGridSize) * snapToGridSize,
ui.position.top = Math.floor((e.pageY - f._wrapper.offset().top) / snapToGridSize) * snapToGridSize
}
}
最佳答案
问题在于您将网格设置的大小不是项目大小的因素。 Here是你的 fiddle ,更新了正确的实现。
我重复了相关代码,如下:
jQuery
$(".draggable").draggable({
grid:[20, 20] // 20 and 20 must be factors of the corresponding dimensions on your item
});
CSS
.draggable{
width:38px; /* Width and Height are both adjusted to account for the border */
height:38px;
border: 1px solid black;
}
如果您决定要防止网格项重叠,则只需将网格大小设置为与网格项本身的大小相同。 Here您的 fiddle 是否更新了这两种解决方案,以便您可以比较它们。
关于javascript - jQuery 可拖动排列网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17431899/