This article only do the translation record view, GitHub original project Address:
https://github.com/RubaXa/Sortable/ , recommended to download to a local Sortable.js examples on GitHub copied to run locally, at http: // jsbin .com is running a lot of time will be reported on Sortable is not defined
the error.
Sortable.js is used in modern browsers and touch devices and drop re-sort the list of JavaScript libraries, support for jQuery, Meteor, AngularJS, React, Polymer, Knockout and compatible with any CSS libraries.
feature
- Support for touch devices and modern browsers (including IE9)
- You can be dragged from one list to another in the same list or
- CSS animations when moving items
- Drag the handle and optional text support
- Intelligent Auto Scroll
- Use the native HTML5 drag and drop API build
- CSS support any library
- Simple API
- Not based on jQuery (but also supported)
installation
By npm
$ npm install sortablejs --save
- 1
use
<ul id="items">
<li>item 1</li> <li>item 2</li> <li>item 3</li> </ul>
var el = document.getElementById('items');
var sortable = Sortable.create(el);
You can use any element of the list and its elements, not just ul
/ li
. This is div
the example .
parameter
the Sortable the sortable new new = var (EL, { Group: "name", or {// name: "...", pull: [to true, to false, clone], PUT: [to true, to false, Array]} Sort: to true // supports sorting in the list list inside the sorting. Delay: 0, // time in milliseconds to define the sort should start in milliseconds to the dEFINE the when time at the the sorting should start. touchStartThreshold: 0, // pixels, in class is canceled within the range of movement of the number of pixels delay drag event PX, How MANY pixels at the Point A dELAYED 32A (g) Should the move the before the drag event. disabled: false, // If set to true, disables the sort disables the sortable if set to true. . Store: null, // Store @see animation:. 150, // ms, the article moving animation speed sorting, `0` indicates no animation ms, animation speed moving items when sorting ,` 0` - without animation handle: ".my-handle", // handle to drag select list item, you can set the list item in a DOM node based on the drag. Selector List items the WITHIN handle the Drag filter: ".IGNORE-Elements", // choose not to support drag selector (String or Function). That do not Lead to Selectors dragging (String or Function) preventOnFilter: to true, // trigger when calling `event.preventDefault` filter` () `. `Event.preventDefault Call ()` `filter` the when triggered draggable with:" .Item ", // specify the elements which items should be draggable. Which items Inside at The Element Specifies Should BE draggable with ghostClass: "Ghost-sortable", when // drag and drop, ahead of the default class name DOM node, in this class can be defined at the appropriate style. The drop placeholder name for class chosenClass: class name "sortable-chosen", when selected // DOM node, this class may define the appropriate style. Class name for the chosen item dragClass: class name "sortable-drag", // drag when the DOM node, this class may define the appropriate style. The name for dragging Item class dataIdAttr: 'Data-ID', forceFallback: false, // ignore HTML5 DnD behavior and force a rollback use. ignore the HTML5 DnD behaviour and force the fallback to kick in the class name "sortable-fallback", when used forceFallback // clone DOM element: fallbackClass. The name for Cloned DOM class When the using the Element forceFallback fallbackOnBody: to false, // cloned DOM elements appended to the Document Body. Cloned the DOM Element at The INTO appends the Document's at The Body fallbackTolerance: 0, // pixels to specify how far to move the mouse should be considered before dragging. How FAR at The pixels in the Specify Should the Move Mouse's the before IT AS A Considered the Drag. The Scroll: to true, // or HTMLElement scrollFn: function (offsetX, offsetY, originalEvent, touchEvt, hoverTargetEl) {...}, // if you have self scrollFn scroll bar can be used to define the automatic scrolling. if you have custom scrollbar scrollFn may be used for autoscrolling scrollSensitivity: 30, // must be close to the edge of the mouse how much px to start rolling. PX, at The Mouse How near to the MUST BE AN Edge to Start scrolling. scrollSpeed: 10, // scroll speed. PX the setData: function (/ * ** the DataTransfer / the dataTransfer, / * ** the HTMLElement / dragEl) { the dataTransfer.setData ( 'the Text', dragEl.textContent); }, // the Element IS Chosen onChoose: function (/ * ** the Event / EVT) { evt.oldIndex; // index WITHIN parent Element }, // the Element Started dragging the onStart: function (/ * ** the Event / EVT) { evt.oldIndex; // index WITHIN parent Element }, // the Element dragging ended onEnd: function (/ * ** the Event / EVT) { var itemEl = evt.item; // dragged the HTMLElement evt.to; // List target evt.from; // previous list evt.oldIndex; // element's old index within old parent evt.newIndex; // element's new index within new parent }, // Element is dropped into the list from another list onAdd: function (/**Event*/evt) { // same properties as onEnd }, // Changed sorting within list onUpdate: function (/**Event*/evt) { // same properties as onEnd }, // Called by any change to the list (add / update / remove) onSort: function (/**Event*/evt) { // same properties as onEnd }, // Element is removed from the list into another list onRemove: function (/**Event*/evt) { // same properties as onEnd }, // Attempt to drag a filtered element onFilter: function (/**Event*/evt) { var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event. }, // Event when you move an item in the list or between lists onMove: function (/**Event*/evt, /**Event*/originalEvent) { // Example: http://jsbin.com/tuyafe/1/edit?js,output evt.dragged; // dragged HTMLElement evt.draggedRect; // TextRectangle {left, top, right и bottom} evt.related; // HTMLElement on which have guided evt.relatedRect; // TextRectangle originalEvent.clientY; // mouse position // return false; — for cancel }, // Called when creating a clone of element onClone: function (/**Event*/evt) { var origEl = evt.item; var cloneEl = evt.clone; } });
group
To drag elements from one list to another, the two lists group must have the same value. You can also define whether the list can give, offer and keep a copy (clone) and receiving elements.
name
:String
- Group namepull
:true|false|'clone'|function
- the ability to move from the list. clone - copy items, instead of moving.put
:true|false|["foo", "bar"]|function
- Can you add other elements from the list, or you can obtain the group name from the array elements.revertClone
:boolean
- moved to another list, the cloned element will be restored to the initial position.
sort
Sort the list.
delay
When sorting define the start time (in milliseconds).
touchStartThreshold
This option is fallbackTolerance
similar to options.
After the delay set this option, even if your fingers are not moving, some of which have very sensitive touch screen phones (eg Samsung Galaxy S8) will also trigger unwanted touch motion events leading to the sort can not be triggered.
This option sets the minimum pointer that must occur before canceling delayed sorting move.
Preferably between 3 to 5.
disabled
If set true
, disable sortable.
var sortable = Sortable.create(list);
document.getElementById("switcher").onclick = function () { var state = sortable.option("disabled"); // get sortable.option("disabled", !state); // set };
handle
To make the list item draggable, Sortable disables the user's text selection. This is not always satisfactory. To allow a text selection, the definition of drag handler, the handler is allowed to drag the region of each list element.
<ul>
<li><span class="my-handle">::</span> list item text one <li><span class="my-handle">::</span> list item text two </ul>
Sortable.create(el, {
handle: ".my-handle" });
.my-handle {
cursor: move; cursor: -webkit-grabbing; }
filter
Sortable.create(list, {
filter: ".js-remove, .js-edit",
onFilter: function (evt) {
var item = evt.item,
ctrl = evt.target;
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
item.parentNode.removeChild(item); // remove sortable item
}
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link // ... } } })
ghostClass
Placing placeholder class name (default sortable-ghost
).
.ghost {
opacity: 0.4; }
Sortable.create(list, {
ghostClass: "ghost" });
chosenClass
DOM node name of the selected class (default sortable-chosen
).
.chosen {
color: #fff; background-color: #c00; }
Sortable.create(list, {
delay: 500, chosenClass: "chosen" });
forceFallback
If set to true, even if we use the HTML5 browser, will also use the reserve non-HTML5 browsers. This makes it possible for us to test the behavior of older browsers, even in newer browsers, you can also make Drag'n Drop more consistent between the desktop, mobile and old browsers.
The most important thing is, Fallback is always a copy of the DOM element, and additional classes fallbackClass defined in the options. This behavior control the appearance of this "drag" elements.
fallbackTolerance
Mimic the native resistance threshold. In pixels specify how far to move the mouse should be considered before dragging the unit. If the project can also click the link in the list, very useful.
When users click the sortable element, moving a little uncommon in between the time you press and release time. Only when you move the pointer beyond a certain tolerance will begin to drag, so you do not accidentally every time you click to start dragging.
Preferably between 3 to 5.
scroll
If set true
, the page (or sorting area) upon reaching the edge of the scroll.
scrollFn
It will be used to define the automatic scrolling feature. Use default el.scrollTop / el.scrollLeft
. There are useful custom scrollbars and dedicated scrolling function.
scrollSensitivity
Custom mouse must be close to the edge to begin rolling manner.
scrollSpeed
The mouse pointer enters the scrollSensitivity
window should scroll speed after the distance.
Event Object
to
:HTMLElement
- List, which moved elements.from
:HTMLElement
- existed before the listitem
:HTMLElement
- drag elementclone
:HTMLElement
oldIndex
:Number|undefined
- the parent of the old indexnewIndex
:Number|undefined
- the parent of the new index
move —- event object
to
:HTMLElement
from
:HTMLElement
dragged
:HTMLElement
draggedRect
:TextRectangle
related
:HTMLElement
- guiding elementrelatedRect
:TextRectangle
Method
option(name:String[, value:]):
Gets or sets the options.
closest(el:String[, selector:HTMLElement]):HTMLElement|null
For each element in the set, by the test element itself and traverse the DOM tree to get the first ancestor elements matching the selector.
toArray():String[]
The sort item may be a data-id (dataIdAttr option) sequence into an array of strings.
sort(order:String[])
Sort elements from the array.
var order = sortable.toArray();
sortable.sort(order.reverse()); // apply
- 1
- 2
save()
Save the current sort
destroy()
Sortable completely delete function.
Store
Save and restore order.
<ul>
<li data-id="1">order</li> <li data-id="2">save</li> <li data-id="3">restore</li> </ul>
Sortable.create(el, {
group: "localStorage-example",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name); return order ? order.split('|') : []; }, /** * Save the order of elements. Called onEnd (when the item is dropped). * @param {Sortable} sortable */ set: function (sortable) { var order = sortable.toArray(); localStorage.setItem(sortable.options.group.name, order.join('|')); } } })
Static methods and properties
Sortable.create(el:HTMLElement[, options:Object]):Sortable
Create a new instance.
Sortable.active:Sortable
Linked to an active instance.
Sortable.utils
on(el:HTMLElement, event:String, fn:Function)
- Additional event handlersoff(el:HTMLElement, event:String, fn:Function)
- Remove the event handlercss(el:HTMLElement):Object
- Get all the CSS property valuescss(el:HTMLElement, prop:String):Mixed
- Get style property valuescss(el:HTMLElement, prop:String, value:String)
- Set a CSS propertycss(el:HTMLElement, props:Object)
- More Set CSS propertiesfind(ctx:HTMLElement, tagName:String[, iterator:Function]):Array
- Get elements by tag namebind(ctx:Mixed, fn:Function):Function
- T Gets a function that returns a function and always with a specific contextis(el:HTMLElement, selector:String):Boolean
- Check the current matched set of elements for selectorsclosest(el:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Null
- for each element in the collection, by the test element itself and traverse the DOM tree to get the first ancestor element matches the selectorclone(el:HTMLElement):HTMLElement
- create a matching set of elements deep copytoggleClass(el:HTMLElement, name:String, state:Boolean)
- Add or remove an element from each class
CDN
<!-- jsDelivr :: Sortable (https://www.jsdelivr.com/package/npm/sortablejs) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js"></script> <!-- jsDelivr :: Sortable :: Latest (https://www.jsdelivr.com/package/npm/sortablejs) --> <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
jQuery compatibility
To assemble jQuery plugin, perform the following steps:
cd Sortable
npm install
grunt jquery
Now you can use jquery.fn.sortable.js :(
or jquery.fn.sortable.min.js If you run a grunt jquery: min)
$("#list").sortable({ /* options */ }); // init
$("#list").sortable("widget"); // get Sortable instance $("#list").sortable("destroy"); // destroy Sortable instance $("#list").sortable("{method-name}"); // call an instance method $("#list").sortable("{method-name}", "foo", "bar"); // call an instance method with parameters
参考:https://blog.csdn.net/fxss5201/article/details/82528189