---
title: "jQuery Gridly 拖拽排序插件获得拖动的位置"
author: "ranyut"
date: "2015-12-11T10:42:43Z"
tags: []
categories: ["Web前端"]
slug: "jquery-gridly"
draft: false
lastmod: "2016-02-14T10:46:56Z"
id: 2263347
url: "https://just4java.iteye.com/blog/2263347"
---

jQuery Gridly 拖拽排序插件获得拖动的位置

Installation

To install download one of these packages and include the jquery.gridly.js and jquery.gridly.css files in your head with the following:

 

 **github:** [https://github.com/ksylvest/jquery-gridly](https://github.com/ksylvest/jquery-gridly)

 

1. &lt;scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"type="text/javascript"&gt;&lt;/script&gt;
2. &lt;scriptsrc="javascript/jquery.gridly.js"type="text/javascript"&gt;&lt;/script&gt;
3. &lt;linkhref="stylesheets/jquery.gridly.css"rel="stylesheet"type="text/css"/&gt;

## Example

Setting up a gridly is easy. The following snippet is a good start:

01. &lt;style type="text/css"&gt;
02. .gridly {
03. position: relative;
04. width: 960px;
05. }
06. .brick.small {
07. width: 140px;
08. height: 140px;
09. }
10. .brick.large {
11. width: 300px;
12. height: 300px;
13. }
14. &lt;/style&gt;
15. &lt;div class="gridly"&gt;
16. &lt;div class="brick small"&gt;&lt;/div&gt;
17. &lt;div class="brick small"&gt;&lt;/div&gt;
18. &lt;div class="brick large"&gt;&lt;/div&gt;
19. &lt;div class="brick small"&gt;&lt;/div&gt;
20. &lt;div class="brick small"&gt;&lt;/div&gt;
21. &lt;div class="brick large"&gt;&lt;/div&gt;
22. &lt;/div&gt;
23. &lt;script&gt;
24. $('.gridly').gridly({
25. base: 60, // px
26. gutter: 20, // px
27. columns: 12
28. });
29. &lt;/script&gt;

 

可以进行拖动、排序，动态效果。

 

怎么获取拖动的位置，进行排序保存呢？

之前有人说获取不到，实际上是可以的，通过两个回调函数实现，reordering拖动前回调，reordered拖动后回调。在初时化时需要这样指定：

1. //初始化设置
2. $('.gridly').gridly({
3. callbacks:{ reordering: reordering , reordered: reordered }
4. });​​

 

回调函数实例：

01. //拖动前回调
02. var reordering =function($elements){
03. // Called before the drag and drop starts with the elements in their starting position.
04. //alert('start');
05. };
06. //拖动后回调
07. var reordered =function($elements){
08. // Called after the drag and drop ends with the elements in their ending position.
09. // 当前对象
10. var currentObj =this.reordered.arguments\[1];
11. var currentId = currentObj\[0].id;
12. alert('拖动对象：'+ currentId);
13. var arr = $elements;
14. // 前一个对象
15. var prevObj;
16. // 后一个对象
17. var afterObj;
18. for(i =0; i &lt; arr.length; i++){
19. if(arr\[i].id == currentId){
20. if(i &gt;0){
21. prevObj = arr\[i -1];
22. }
23. if(i +1&lt; arr.length){
24. afterObj = arr\[i+1];
25. }
26. }
27. }
28. if(prevObj !=undefined){
29. alert('前一个对象：'+ prevObj.id)
30. }
31. if(afterObj !=undefined){
32. alert('后一个对象：'+ afterObj.id);
33. }
34. //执行保存排序，更新数据
35. //sortData...
36. };
37. //初始化设置
38. $('.gridly').gridly({
39. callbacks: { reordering: reordering , reordered: reordered }
40. });​

 

在回调函数里得到了拖动的对象及前后位置的对象就可以知道位置了，再执行更新数据保存排序即可。

 

按官方文档做一个例子，可以下载附件 jquery-gridly-callback