JqueryUI - 可拖动


jQueryUI 提供了draggable()方法来使任何DOM 元素可拖动。一旦元素可拖动,您就可以通过用鼠标单击该元素并将其拖动到视口中的任意位置来移动该元素。

句法

Draggable ()方法可以以两种形式使用 -

$(selector, context).draggable(options) 方法

Draggable (options)方法声明一个HTML元素可以在HTML页面中移动。options参数是一个对象,它指定涉及元素的Behave。

句法

$(selector, context).draggable(options);

您可以使用 Javascript 对象一次提供一个或多个选项。如果要提供多个选项,那么您将使用逗号分隔它们,如下所示 -

$(selector, context).draggable({option1: value1, option2: value2..... });

下表列出了可以与此方法一起使用的不同选项-

先生。 选项和说明
1 添加类

如果此选项设置为false,它将阻止ui-draggable类添加到所选 DOM 元素列表中。默认情况下它的值为true

选项 - addClasses

如果此选项设置为false,它将阻止ui-draggable类添加到所选 DOM 元素列表中。默认情况下它的值为true

句法

$(".selector").draggable(
   { addClasses: false }
);
2 附加到

指定拖动时应将可拖动帮助器附加到的元素。默认情况下它的值为“parent”。

选项 - 追加到

指定拖动时应将可拖动帮助器附加到的元素。默认情况下它的值为“parent”。

句法

$(".selector").draggable(
   { appendTo: "body"}
);
3

此选项限制拖动到水平 (x) 或垂直 (y) 轴。可能的值:“x”、“y”。

选项 - 轴

此选项限制拖动到水平 (x) 或垂直 (y) 轴。可能的值:“x”、“y”。

句法

$(".selector").draggable(
   { axis: "x" }
);
4 取消

您可以使用此选项来防止从指定元素开始拖动。默认情况下,其值为“输入、文本区域、按钮、选择、选项”。

选项 - 取消

您可以使用此选项来防止从指定元素开始拖动。默认情况下它的值为“input,textarea,button,select,option”

句法

$(".selector").draggable(
   { cancel: ".title" }
);
5 连接到可排序

您可以使用此选项来指定其元素可互换的列表。在放置结束时,该元素是列表的一部分。默认情况下其值为“false”。

选项 - connectToSortable

您可以使用此选项来指定其元素可互换的列表。在放置结束时,该元素是列表的一部分。默认情况下其值为“false”。

句法

$(".selector").draggable(
   { connectToSortable: "#my-sortable" }
);
6 遏制

将拖动限制在指定元素或区域的范围内。默认情况下其值为“false”。

选项 - 遏制

将拖动限制在指定元素或区域的范围内。默认情况下其值为“false”。

句法

$(".selector").draggable(
   { containment: "parent" }
);
7 光标

指定元素移动时光标的 CSS 属性。它代表鼠标指针的形状。默认情况下,其值为“自动”。

选项 - 光标

指定元素移动时光标的 CSS 属性。它代表鼠标指针的形状。默认情况下,其值为“自动”。其他可能的值是 -

  • “十字准线”(交叉)
  • “默认”(箭头)
  • “指针”(手)
  • “移动”(两个箭头交叉)
  • “e-resize”(向右扩展)
  • “ne-resize”(向右展开)
  • “nw-resize”(向左扩展)
  • “n-resize”(向上扩展)
  • “se-resize”(向右下方展开)
  • "sw-resize" (expand down left)
  • "s-resize" (expand down)
  • "auto" (default)
  • "w-resize" (expand left)
  • "text" (pointer to write text)
  • "wait" (hourglass)
  • "help" (help pointer)

Syntax

$(".selector").draggable(
   { cursor: "crosshair" }
);
8 光标处

设置拖动助手相对于鼠标光标的偏移。坐标可以使用一个或两个键的组合以散列形式给出:{top、left、right、bottom}。默认情况下其值为“false”。

Option - cursorAt

Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. By default its value is "false".

Syntax

$(".selector").draggable(
   $( ".selector" ).draggable({ cursorAt: { left: 5 } });
);
9 延迟

延迟(以毫秒为单位),之后考虑鼠标的第一次移动。位移可能会在该时间之后开始。默认情况下其值为“0”。

Option - delay

Delay, in milliseconds, after which the first movement of the mouse is taken into account. The displacement may begin after that time. By default its value is "0".

Syntax

$(".selector").draggable(
   { delay: 300 }
);
10 残疾人

设置为 true 时,将禁用移动项目的功能。除非启用此功能(使用可拖动(“启用”)指令),否则无法移动项目。默认情况下其值为“false”。

Option - disabled

When set to true, disables the ability to move items. Items cannot be moved until this function is enabled (using the draggable ("enable") instruction). By default its value is "false".

Syntax

$(".selector").draggable(
   { disabled: true }
);
11 距离

在考虑位移之前鼠标必须移动的像素数。默认情况下其值为“1”。

Option - distance

Number of pixels that the mouse must be moved before the displacement is taken into account. By default its value is "false".

Syntax

$(".selector").draggable(
   { distance: 10 }
);
12 网格

将拖动助手捕捉到网格,每个 x 和 y 像素。该数组必须采用 [ x, y ] 形式。默认情况下其值为“false”。

Option - grid

Snaps the dragging helper to a grid, every x and y pixels. The array must be of the form [ x, y ]. By default its value is "false".

Syntax

$(".selector").draggable(
   { grid: [ 50, 20 ] }
);
13 处理

如果指定,则限制从开始拖动,除非在指定元素上发生鼠标按下。默认情况下其值为“false”。

Option - handle

If specified, restricts dragging from starting unless the mousedown occurs on the specified element(s). By default its value is "false".

Syntax

$(".selector").draggable(
   { handle: "h2" }
);
14 帮手

允许使用辅助元素来拖动显示。默认情况下,其值为“原始”。

Option - helper

Allows for a helper element to be used for dragging display. By default its value is "original".

Syntax

$(".selector").draggable(
   { helper: "clone" }
);
15 iframe修复

防止 iframe 在拖动过程中捕获 mousemove 事件。默认情况下其值为“false”。

Option - iframeFix

Prevent iframes from capturing the mousemove events during a drag. By default its value is "false".

Syntax

$(".selector").draggable(
   { iframeFix: true }
);
16 不透明度

移动时元素移动的不透明度。默认情况下其值为“false”。

Option - opacity

Opacity of the element moved when moving. By default its value is "false".

Syntax

$(".selector").draggable(
   {  opacity: 0.35 }
);
17 号 刷新位置

如果设置为true,则每次鼠标移动时都会计算所有可放置位置。默认情况下其值为“false”。

Option - refreshPositions

If set to true, all droppable positions are calculated on every mousemove. By default its value is "false".

Syntax

$(".selector").draggable(
   { refreshPositions: true }
);
18 恢复

指示元素是否在移动结束时移回其原始位置。默认情况下其值为“false”。

Option - revert

Indicates whether the element is moved back to its original position at the end of the move. By default its value is "false".

Syntax

$(".selector").draggable(
   { revert: true }
);
19 恢复持续时间

元素返回到其原始位置之前的位移持续时间(以毫秒为单位)(请参阅 options.revert)。默认情况下其值为“500”。

Option - revertDuration

Duration of displacement (in milliseconds) after which the element returns to its original position (see options.revert). By default its value is "500".

Syntax

$(".selector").draggable(
   { revertDuration: 200 }
);
20 范围

除了 droppable 的接受选项之外,还用于对可拖动和可放置的项目集进行分组。默认情况下,其值为“默认”。

Option - scope

Used to group sets of draggable and droppable items, in addition to droppable's accept option. By default its value is "default".

Syntax

$(".selector").draggable(
   { scope: "tasks" }
);
21 滚动

当设置为true(默认值)时,如果项目移到窗口可视区域之外,显示将滚动。默认情况下其值为“true”。

Option - scroll

When set to true (the default), the display will scroll if the item is moved outside the viewable area of the window. By default its value is "true".

Syntax

$(".selector").draggable(
   { scroll: false }
);
22 滚动灵敏度

指示鼠标必须退出窗口多少像素才能导致显示滚动。默认情况下其值为“20”。

Option - scrollSensitivity

Indicates how many pixels the mouse must exit the window to cause scrolling of the display. By default its value is "20".

Syntax

$(".selector").draggable(
   { scrollSensitivity: 100 }
);
23 滚动速度

指示滚动开始后显示屏的滚动速度。默认情况下其值为“20”。

Option - scrollSpeed

Indicates the scrolling speed of the display once scrolling begins. By default its value is "20".

Syntax

$(".selector").draggable(
   { scrollSpeed: 100 }
);
24 折断

调整在其他元素(飞行的)上移动的项目的显示。默认情况下其值为“false”。

Option - snap

Adjusts the display of the item being moved on other elements (which are flown). By default its value is "false".

Syntax

$(".selector").draggable(
   { snap: true }
);
25 捕捉模式

指定如何在移动的元素和options.snap中指示的元素之间进行调整。默认情况下,其值为“两者”。

Option - snapMode

>Specifies how the adjustment should be made between the moved element and those indicated in options.snap. By default its value is "both".

Syntax

$(".selector").draggable(
   { snapMode: "inner" }
);
26 咬合公差

建立调整所需的位置差异的最大像素数。默认情况下其值为“20”。

Option - snapTolerance

Maximum number of pixels in the difference in position necessary to establish the adjustment. By default its value is "20".

Syntax

$(".selector").draggable(
   { snapTolerance: 30 }
);
27

控制与选择器匹配的元素集的 z-index,始终将当前拖动的项目置于前面。在窗口管理器等方面非常有用。默认情况下其值为“false”。

Option - stack

Controls the z-index of the set of elements that match the selector, always brings the currently dragged item to the front. Very useful in things like window managers. By default its value is "false".

Syntax

$(".selector").draggable(
   { stack: ".products"  }
);
28 z索引

被拖动时助手的 Z 索引。默认情况下其值为“false”。

Option - zIndex

Z-index for the helper while being dragged. By default its value is "false".

Syntax

$(".selector").draggable(
   { zIndex: 100 }
);

以下部分将向您展示拖动功能的一些工作示例。

默认功能

以下示例演示了一个不向draggable()方法传递任何参数的draggable 功能的简单示例。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" 
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      
      <style>
         #draggable { width: 150px; height: 150px; padding: 0.5em; background:#eee;}
      </style>
      
      <script>
         $(function() {
            $( "#draggable" ).draggable();
         });
      </script>
   </head>
   
   <body>
      <div id = "draggable" class = "ui-widget-content">
         <p>Drag me !!!</p>
      </div>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它。您还必须看到以下输出。现在,您可以使用结果 -

使用禁用、距离和延迟

下面的示例展示了JqueryUI 的拖动功能中三个重要选项(a)禁用(b)延迟(c)距离的用法。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>
   
   <body>
      <div id = "div1" style = "border:solid 1px;background-color:gainsboro;">
         <span>You can't move me!</span><br /><br />
      </div>
      <div id = "div2" style = "border:solid 1px;background-color:grey;">
         <span>
            Dragging will start only after you drag me for 50px
         </span>
         <br /><br />
      </div>
      <div id = "div3" style = "border:solid 1px;background-color:gainsboro;">
         <span>
            You have to wait for 500ms for dragging to start!
         </span>
         <br /><br />
      </div>

      <script>
         $("#div1 span").draggable (
            { disabled: true }
         );
         $("#div2 span").draggable (
            { distance: 50 }
         );
         $("#div3 span").draggable (
            { delay: 500 }
         );
      </script>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它,您应该看到以下输出。现在,您可以使用结果 -

限制运动

下面的示例展示了如何使用 JqueryUI 的拖动功能中的包含选项来限制屏幕上元素的移动。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>
      
   <body>
      <div id = "div4" style = "border:solid 1px;background-color:gainsboro;">
         <span>You can drag me only within this div.</span><br /><br />
      </div>
      <div id = "div5" style = "border:solid 1px;background-color:grey;">
         <span>You can drag me only along x axis.</span><br /><br />
      </div>

      <script>
         $("#div4 span").draggable ({
            containment : "#div4"
         });
         $("#div5 span").draggable ({
            axis : "x"
         });
      </script>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它。它应该产生以下输出。现在,您可以使用输出 -

这里,<span>元素被阻止超出ID为div4的<div>。您还可以使用值为“x”或“y”的选项对垂直或水平运动施加约束,这也得到了演示。

通过复制来移动内容

以下示例演示如何移动作为所选元素的克隆的项目。这是使用带有值clone的选项帮助器完成的。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>
   
   <body>
      <div id = "div6" style = "border:solid 1px;background:#eee; height:50px;">
         <span>You can duplicate me....</span>
      </div>
      
      <script>
         $("#div6 span").draggable ({
            helper : "clone"
         });
      </script>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它,您还必须看到以下输出 -

正如您所看到的,当拖动第一个元素时,只有克隆的元素移动,而原始项目保持不变。如果释放鼠标,克隆的元素就会消失,而原始项目仍位于其原始位置。

获取当前期权价值

以下示例演示了如何在脚本执行期间随时获取任何选项的值。这里我们将读取执行时设置的cursorcursorAt选项的值。以类似的方式,您可以获得任何其他可用选项的价值。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>

   <body>
      <div id = "divX" style = "border:solid 1px;background:#eee; height:50px;">
         <span>Click anywhere on me to see cursor type...</span>
      </div>

      <script>
         /* First make the item draggable */
         $("#divX span").draggable();

         $("#divX span").bind('click', function( event ) {
            var cursor = $( "#divX span" ).draggable( "option", "cursor" );
            var cursorAt = $( "#divX span" ).draggable( "option", "cursorAt" );
            alert("Cursor type - " + cursor + ", cursorAt - " + cursorAt);
         });
      </script>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它,您还必须看到以下输出 -

$(selector, context).draggable("action", [params]) 方法

Draggable (action, params)方法可以对可移动元素执行操作,例如防止位移。该操作在第一个参数中指定为字符串,并且可以根据给定的操作提供一个或多个参数(可选)。

基本上,这里的操作什么都不是,只是我们可以以字符串形式使用的 jQuery 方法。

句法

$(selector, context).draggable ("action", [params]);

下表列出了此方法的操作 -

先生。 动作与描述
1 破坏()

Remove drag functionality completely. The elements are no longer movable. This will return the element back to its pre-init state.

Action - destroy()

Remove drag functionality completely. The elements are no longer movable. This will return the element back to its pre-init state.

Syntax

$(".selector").draggable("destroy");
2 disable()

Disable drag functionality. Elements cannot be moved until the next call to the draggable("enable") method.

Action - disable()

Disable drag functionality. Elements cannot be moved until the next call to the draggable("enable") method.

Syntax

$(".selector").draggable("disable");
3 enable()

Reactivates drag management. The elements can be moved again.

Action - enable()

Reactivates drag management. The elements can be moved again.

Syntax

$(".selector").draggable("enable");
4 option(optionName)

Gets the value currently associated with the specified optionName. Where optionName is name of the option to get and is of type String.

Action - option(optionName)

Gets the value currently associated with the specified optionName. Where optionName is name of the option to get and is of type String.

Syntax

var isDisabled = $( ".selector" ).draggable( "option", "disabled" );
5 option()

Gets an object containing key/value pairs representing the current draggable options hash.

Action - option()

Gets an object containing key/value pairs representing the current draggable options hash.

Syntax

var options = $( ".selector" ).draggable( "option" );
6 option(optionName, value)

Sets the value of the draggable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option.

Action - option(optionName, value)

Sets the value of the draggable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option.

Syntax

$( ".selector" ).draggable( "option", "disabled", true );
7 option(options)

Sets one or more options for the draggable. Where options is a map of option-value pairs to set.

Action - option(options)

Sets one or more options for the draggable. Where options is a map of option-value pairs to set.

Syntax

$(".selector").draggable("option", { disabled: true } );
8 widget()

Returns a jQuery object containing the draggable element.

Action - widget()

Returns a jQuery object containing the draggable element.

Syntax

var widget = $(".selector ).draggable("widget");

Example

Now let us see an example using the actions from the above table. The following example demonstrates the use of actions disable and enable.

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>
   
   <body>
      <div id = "div7" style = "border:solid 1px;background-color:gainsboro;">
         <span>You can't move me. Dragging is disabled.</span><br><br>
      </div>
      <div id = "div8" style = "border:solid 1px;background-color:grey;">
         <span>You can move me. Dragging is enabled.</span><br><br>
      </div>
      
      <script>
         $("#div7 span").draggable ();
         $("#div7 span").draggable ('disable');
         $("#div8 span").draggable ();
         $("#div8 span").draggable ('enable');
      </script>
   </body>
</html>

Let us save the above code in an HTML file dragexample.htm and open it in a standard browser which supports javascript, you should see the following output −

As you can see first element is disabled and the second element's dragging is enabled which you can try to drag.

Event Management on the Moved elements

In addition to the draggable (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −

Sr.No. Event Method & Description
1 create(event, ui)

Triggered when the draggable is created. Where event is of type Event, and ui is of type Object.

Event - create(event, ui)

Triggered when the draggable is created. Where event is of type Event, and ui is of type Object.

Syntax

$(".selector").draggable(
   create: function(event, ui) {}
);
2 drag(event, ui)

Triggered while the mouse is moved during the dragging. Where event is of type Event, and ui is of type Object like helper, position, offset.

Event - drag(event, ui)

Triggered while the mouse is moved during the dragging. Where event is of type Event, and ui is of type Object like helper, position, offset.

Syntax

$(".selector").draggable(
   drag: function(event, ui) {}
);
3 start(event, ui)

Triggered when dragging starts. Where event is of type Event, and ui is of type Object like helper, position, offset.

Event - start(event, ui)

Triggered when dragging starts. Where event is of type Event, and ui is of type Object like helper, position, offset.

Syntax

$(".selector").draggable(
   start: function( event, ui ) {}
);
4 stop(event, ui)

Triggered when dragging stops. Where event is of type Event, and ui is of type Object like helper, position, offset.

Event - stop(event, ui)

Triggered when dragging stops. Where event is of type Event, and ui is of type Object like helper, position, offset.

Syntax

$(".selector").draggable(
   stop: function( event, ui ) {}
);

Example

以下示例演示了在拖动功能期间使用事件方法。此示例演示了拖动事件的使用。

<!DOCTYPE html>
<html>
   <head>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   </head>
   
   <body>
      <div id = "div9" style = "border:solid 1px;background-color:gainsboro;">
         <span>Drag me to check the event method firing</span><br /><br />
      </div>
      
      <script>
         $("#div9 span").draggable ({
            cursor: "move",
            axis : "x",
            drag: function( event, ui ) {
               alert("hi..");
            }
         });
      </script>
   </body>
</html>

让我们将上面的代码保存在 HTML 文件Dragexample.htm中,并在支持 JavaScript 的标准浏览器中打开它,您应该得到以下输出 -

现在尝试拖动写入的内容,您将看到拖动事件的开始被触发,这会导致显示一个对话框,并且光标将更改为移动图标,并且文本将仅在 X 轴上移动。