---
title: "jquery ui（六）拖动排序 sortable "
author: "dearkerwin"
date: "2013-08-29T13:31:56Z"
tags: []
categories: ["Web前端"]
slug: "jquery-ui-sortable"
draft: false
lastmod: "2013-08-29T13:31:56Z"
id: 1933265
url: "https://dearkerwin.iteye.com/blog/1933265"
---

jquery ui 的另一个强大的功能就是拖动排序，也就是通过鼠标的拖到，实现对一些元素的排序。  
废话少说，用实例说话。

## 一、简单的实例

下面是对一组li元素进行排序的实例

### 1、代码

  &lt;style&gt;  
  //为了展示的效果更好，增加了一些css样式  
.sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }  
.sortable li { margin: 0 3px 3px 3px; padding: 0.4em;   
           padding-left: 1.5em; font-size: 1.4em; height: 18px; cursor: move ; }  
.sortable li span { position: absolute; margin-left: -1.3em; }  
.ui-state-highlight { height: 1.5em; line-height: 1.2em; }  
  &lt;/style&gt;

  &lt;script&gt;  
  $(function() {  
    $( ".sortable" ).sortable();  
  });  
  &lt;/script&gt;

  &lt;ul class="sortable"&gt;  
    &lt;li class="ui-state-default"&gt;Item 1--ifxoxo.com&lt;/li&gt;  
    &lt;li class="ui-state-default"&gt;Item 2--ifxoxo.com&lt;/li&gt;  
    &lt;li class="ui-state-default"&gt;Item 3--ifxoxo.com&lt;/li&gt;  
  &lt;/ul&gt;

### 2、截图

#### （1）拖拽排序之前

[![jquery-ui-sortable 拖拽之前截图 -- ifxoxo.com](http://ifxoxo.com/wp-content/uploads/2013/08/before.jpg)](http://ifxoxo.com/wp-content/uploads/2013/08/before.jpg)

jquery-ui-sortable 拖拽之前截图 — ifxoxo.com

#### （2）拖拽排序的过程

[![jquery-ui-sortable 拖拽过程截图 -- ifxoxo.com](http://ifxoxo.com/wp-content/uploads/2013/08/ing.jpg)](http://ifxoxo.com/wp-content/uploads/2013/08/ing.jpg)

jquery-ui-sortable 拖拽过程截图 — ifxoxo.com

#### （3）拖拽排序之后

[![jquery-ui-sortable 拖拽排序之后 -- ifxoxo.com](http://ifxoxo.com/wp-content/uploads/2013/08/after.jpg)](http://ifxoxo.com/wp-content/uploads/2013/08/after.jpg)

jquery-ui-sortable 拖拽排序之后 — ifxoxo.com

## 二、具体实现

### 1、需要加载文件

(1)jquery.js  
(2)jquery.ui  
(3)jquery.ui的css

&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"&gt;&lt;/script&gt;  
&lt;script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"&gt;&lt;/script&gt;  
&lt;[link](http://www.php.net/link) href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"   
      rel="stylesheet" /&gt;

### 2、页面上的HTML代码

需要一个&lt; div &gt;或者&lt; ul &gt;等元素， 它的直接子节点将可以被拖拽排序

 &lt;ul id="sortable"&gt;  
    &lt;li class="ui-state-default"&gt;Item 1--ifxoxo.com&lt;/li&gt;  
    &lt;li class="ui-state-default"&gt;Item 2--ifxoxo.com&lt;/li&gt;  
    &lt;li class="ui-state-default"&gt;Item 3--ifxoxo.com&lt;/li&gt;  
  &lt;/ul&gt;  
//或者  
&lt;div id="sortable"&gt;  
  &lt;img src="1.jpg"&gt;  
  &lt;img src="2.jpg"&gt;  
  &lt;img src="3.jpg"&gt;  
&lt;/div&gt;

### 3、js代码

最简单的初始化函数：

$(.selecter).sortable()

（它支持很多参数，详见4）

### 4、sortable的参数

（为了更好的解释一些参数，有一个复杂的示例，详见6）

 参数  默认值  作用  axis  false  如果有设置，则元素仅能横向或纵向拖动。可选值：’x', ‘y’  cancel  input,textarea,  
button,select,option  阻止排序动作在匹配的元素上发生 connectWith false 允许sortable对象连接另一个sortable对象，可将item元素拖拽到另一个中.(类型：Selector) containment false 约束排序动作只能在一个指定的范围内发生。可选值：DOM对象, ‘parent’, ‘document’, ‘window’, 或jQuery对象 cursor auto 定义在开始排序动作时，鼠标的样式。  
如 cursor: “move” cursorAt false 当开始移动时，元素的偏移的位置（最多两个方向）。可选值：{ top, left, right, bottom }。  
如 cursorAt: {left:5,bottom:5} delay 0 以毫秒为单位，设置延迟多久才激活排序动作。此参数可防止误点击。  
如 delay: 500 distance 1 决定至少要在元素上面拖动多少像素后，才正式触发排序动作。  
如 distance: 30 dropOnEmpty false 是否允許拖拽到一個空的sortable对象中。 grid false 每次移动都按一个格子大小移动，数组值：\[x,y]  
如 grid: \[50, 20] handle false 限制排序的动作只能在item元素中的某种元素  
如 handle: ‘h2′ helper original 设置是否在拖拽元素时，显示一个辅助的元素。可选值：‘original’, ‘clone’。  
如 helper: ‘clone’ items “&gt; \*” (第一级子元素) 指定在排序对象中，哪些元素是可以进行拖拽排序的。  
如 items: “&gt; li” opacity false 辅助元素(helper)显示的透明度  
如 opacity: 0.6 placeholder false 设置当排序动作发生时，空白占位符的CSS样式  
如 placeholder: ‘css-class-name’ （指定一个css的class） revert false 如果设置成true，则被拖拽的元素在返回新位置时，会有一个动画效果 scroll false 如果设置成true，则元素被拖动到页面边缘时，会自动滚动。 scrollSensitivity 20 设置当元素移动至边缘多少像素时，便开始滚动页面 scrollSpeed 20 设置页面滚动的速度 tolerance intersect 设置当拖动元素越过其它元素多少时便对元素进行重新排序。可选值：’intersect’, ‘pointer’  
intersect：至少重叠50%  
pointer：鼠标指针重叠元素 zIndex 1000 设置在排序动作发生时，元素的z-index值

### 5、事件和方法

（为了更好的解释一些事件和方法，有一个复杂的示例，详见6）

#### （1）事件

**start**  
当排序动作开始时触发此事件。  
定义：$(‘.selector’).sortable({ start: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortstart’, function(event, ui) { … });

**sort**  
当元素发生排序时触发此事件。  
定义：$(‘.selector’).sortable({ sort: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sort’, function(event, ui) { … });

**change**  
当元素发生排序且坐标已发生改变时触发此事件。  
定义：$(‘.selector’).sortable({ change: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortchange’, function(event, ui) { … });

**beforeStop**  
当排序动作结束之前触发此事件。此时占位符元素和辅助元素仍有效。  
定义：$(‘.selector’).sortable({ beforeStop: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortbeforeStop’, function(event, ui) { … });

**stop**  
当排序动作结束时触发此事件。  
定义：$(‘.selector’).sortable({ stop: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortstop’, function(event, ui) { … });

**update**  
当排序动作结束时且元素坐标已经发生改变时触发此事件。  
定义：$(‘.selector’).sortable({ update: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortupdate’, function(event, ui) { … });

**receive**  
当一个已连接的sortable对象接收到另一个sortable对象的元素后触发此事件。  
定义：$(‘.selector’).sortable({ receive: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortreceive’, function(event, ui) { … });

**over**  
当一个元素拖拽移入另一个sortable对象后触发此事件。  
定义：$(‘.selector’).sortable({ over: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortover’, function(event, ui) { … });

**out**  
当一个元素拖拽移出sortable对象移出并进入另一个sortable对象后触发此事件。  
定义：$(‘.selector’).sortable({ out: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortout’, function(event, ui) { … });

**activate**  
当一个有使用连接的sortable对象开始排序动作时，所有允许的sortable触发此事件。  
定义：$(‘.selector’).sortable({ activate: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortactivate’, function(event, ui) { … });  
**deactivate**  
当一个有使用连接的sortable对象结束排序动作时，所有允许的sortable触发此事件。  
定义：$(‘.selector’).sortable({ deactivate: function(event, ui) { … } });  
绑定：$(‘.selector’).bind(‘sortdeactivate’, function(event, ui) { … });

#### （2）方法

**destory**  
从元素中移除拖拽功能。  
用法：.sortable( ‘destroy’ )

**disable**  
禁用元素的拖拽功能。  
用法：.sortable( ‘disable’ )

**enable**  
启用元素的拖拽功能。  
用法：.sortable( ‘enable’ )

**option**  
获取或设置元素的参数。  
用法：.sortable( ‘option’ , optionName , \[value] )

**serialize**  
获取或设置序列化后的每个item元素的id属性。  
用法：.sortable( ‘serialize’ , \[options] )

**toArray**  
获取序列化后的每个item元素的id属性的数组。  
用法：.sortable( ‘toArray’ ）

**refresh**  
手动重新刷新当前sortable对象的item元素的排序。  
用法：.sortable( ‘refresh’ )

**refreshPositions**  
手动重新刷新当前sortable对象的item元素的坐标，此方法可能会降低性能。  
用法：.sortable( ‘refreshPositions’ )

**cancel**  
取消当前sortable对象中item元素的排序改变。  
用法：.sortable( ‘cancel’ )

#### 6、一个稍微复杂一点的例子：

//效果： 每次排序之后，按顺序把每一项的ID输出来  
&lt;style&gt;  
  .sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }  
  .sortable li { margin: 0 3px 3px 3px; padding: 0.4em;  
         padding-left: 1.5em; font-size: 1.4em; height: 18px; cursor: move ;}  
  .sortable li span { position: absolute; margin-left: -1.3em; }  
  .ui-state-highlight { height: 1.5em; line-height: 1.2em; }  
 &lt;/style&gt;  
 &lt;script&gt;  
  $(function() {  
    $( ".sortable" ).sortable({  
    placeholder: "ui-state-highlight" , //拖动时，用css  
    cursor: "move",  
    items :"li",                        //只是li可以拖动  
    opacity: 0.6,                       //拖动时，透明度为0.6  
    revert: true,                       //释放时，增加动画  
    update : function(event, ui){       //更新排序之后  
        var text= "排序为：";  
        $(".sortable li").[each](http://www.php.net/each)(function(){  
            text = text + $(this).attr("id") + " " ;  
        })  
        alert(text);                //把排序的ID弹出  
    }  
   });  
 });  
&lt;/script&gt;  
&lt;ul class="sortable"&gt;  
  &lt;li class="ui-state-default"  id="item-1"&gt;Item 1--from ifxoxo.com&lt;/li&gt;  
  &lt;li class="ui-state-default"  id="item-2" &gt;Item 2--from ifxoxo.com&lt;/li&gt;  
  &lt;li class="ui-state-default"  id="item-3"&gt;Item 3--from ifxoxo.com&lt;/li&gt;  
  &lt;div class="ui-state-default"&gt; Div 4 -- from &lt;a href="ifxoxo.com"&gt;ifxoxo.com&lt;/a&gt;&lt;/div&gt;  
&lt;/ul&gt;

##### 截图如下：

[![展示排序结果--ifxoxo.com](http://ifxoxo.com/wp-content/uploads/2013/08/QQ%E5%9B%BE%E7%89%8720130818235458.jpg)](http://ifxoxo.com/wp-content/uploads/2013/08/QQ%E5%9B%BE%E7%89%8720130818235458.jpg)

展示排序结果–ifxoxo.com

三、其他jquery ui 文章

[1、jquery ui（一）简介](http://ifxoxo.com/jquery-ui-1.html "jquery ui（一）简介__ifxoxo.com")  
[2、jquery ui（二）拖拽 draggable和droppable](http://ifxoxo.com/jquery-ui-draggable.html "jquery ui（二）拖拽draggable和droppable__ifxoxo.com")  
[3、jquery ui（三）弹出窗口 dialog](http://ifxoxo.com/jquery-ui-dialog.html "jquery ui（三）弹出窗口dralog__ifxoxo.com")  
[4、jquery ui（四）进度条 progressbar](http://ifxoxo.com/jquery-ui-prodressbar.html "jquery ui（四）进度条 progressbar__ifxoxo.com")  
[5、jquery ui（五）日期选择器 datepicker](http://ifxoxo.com/jquery-ui-datepicker.html "jquery ui（五）日期选择器 datepicker__ifxoxo.com")  
[6、jquery ui（六）拖动排序 sortable](http://ifxoxo.com/jquery-ui-sortable.html "jquery ui（六）拖动排序 sortable__ifxoxo.com")