SortableJS- 簡單好用的網頁元素拖曳(drag and drop)及排序(sort)套件

SortableJS 是一個簡單好用的網頁元素拖曳(drag and drop)及排序(sort)套件,使用方式如下:

你可以透過 npm

$ npm install sortablejs --save

或 bower 讀入

$ bower install --save sortablejs

 

接著 import

// Default SortableJS
import Sortable from 'sortablejs';

// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';

// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';

 

也可使用 cdn:

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

 

接著準備以下 html

<ul id="items">
	<li>item 1</li>
	<li>item 2</li>
	<li>item 3</li>
</ul>

 

再套上 plugin 即可:

var el = document.getElementById('items');
var sortable = Sortable.create(el, { /* option */ });

 

option 裡面可以設定的內容可以參考官網說明自己設定。

var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	delayOnTouchOnly: false, // only delay if user is using touch
	touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
	disabled: false, // Disables the sortable if set to true.
	store: null,  // @see Store
	animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
	easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
	handle: ".my-handle",  // Drag handle selector within list items
	filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
	preventOnFilter: true, // Call `event.preventDefault()` when triggered `filter`
	draggable: ".item",  // Specifies which items inside the element should be draggable

	dataIdAttr: 'data-id', // HTML attribute that is used by the `toArray()` method

	ghostClass: "sortable-ghost",  // Class name for the drop placeholder
	chosenClass: "sortable-chosen",  // Class name for the chosen item
	dragClass: "sortable-drag",  // Class name for the dragging item

	swapThreshold: 1, // Threshold of the swap zone
	invertSwap: false, // Will always use inverted swap zone if set to true
	invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
	direction: 'horizontal', // Direction of Sortable (will be detected automatically if not given)

	forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

	fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
	fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
	fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

	dragoverBubble: false,
	removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
	emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


	setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
		dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
	},

	// Element is chosen
	onChoose: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element is unchosen
	onUnchoose: function(/**Event*/evt) {
		// same properties as onEnd
	},

	// Element dragging started
	onStart: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element dragging ended
	onEnd: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		evt.to;    // target list
		evt.from;  // previous list
		evt.oldIndex;  // element's old index within old parent
		evt.newIndex;  // element's new index within new parent
		evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
		evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
		evt.clone // the clone element
		evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
	},

	// 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: https://jsbin.com/nawahef/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // DOMRect {left, top, right, bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // DOMRect
		evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
		originalEvent.clientY; // mouse position
		// return false; — for cancel
		// return -1; — insert before target
		// return 1; — insert after target
		// return true; — keep default insertion point based on the direction
		// return void; — keep default insertion point based on the direction
	},

	// Called when creating a clone of element
	onClone: function (/**Event*/evt) {
		var origEl = evt.item;
		var cloneEl = evt.clone;
	},

	// Called when dragging element changes position
	onChange: function(/**Event*/evt) {
		evt.newIndex // most likely why this event is used is to get the dragging element's current index
		// same properties as onEnd
	}
});

 

 

 

課程推薦

HTML與SEO實戰應用—並以ChatGPT助力提升網站品質與流量

HTML與SEO實戰應用—並以ChatGPT助力提升網站品質與流量

本課程專為希望深入了解 HTML 並有效結合 SEO 策略的學員設計。我們將重點放在 HTML 的深度學習與應用上,同時穿插介紹如何透過搜索引擎優化提升網站能見度。透過即時互動式的直播教學,加上 ChatGPT 的輔助,您將學習到如何建立一個結構優良、美觀且符合 SEO 標準的網站。這不僅會提升網站的用戶體驗,還會大幅提高網站的搜索引擎排名,進而增加訪客流量和潛在客戶。
用AI強化職場競爭力 ChatGPT、Midjourney從入門到精通

用AI強化職場競爭力 ChatGPT、Midjourney從入門到精通

在快速變遷的職場中,提升競爭力成為關鍵。透過引領潮流的AI技術,ChatGPT和Midjourney將助您勇攀高峰。無論您是AI新手還是專家,這個課程將引導您從入門到精通,解密AI的奧秘,並學習如何運用於職場。
GitHub Copilot AI 程式碼編輯工具應用實務班

GitHub Copilot AI 程式碼編輯工具應用實務班

讓學員瞭解有效地使用該工具來加速開發流程、提高程式碼品質和生產力。課程重點放在以 JavaScript 程式語言為例,介紹 Copilot 的基本原理、使用方法和最佳實踐。

輸入折扣碼 TC1456JA 還可以額外獲得 NT$500 優惠喔。

ChatGPT X Clipchamp AI 生成影片、配音與字幕應用實戰班

ChatGPT X Clipchamp AI 生成影片、配音與字幕應用實戰班

掌握Clipchamp AI的操作技巧,靈活運用Clipchamp AI進行影片編輯和創作,實現創意表達和傳播目的。

輸入折扣碼 TC1451JAN 還可以額外獲得 NT$500 優惠喔。

如何串接多種數位工具資訊?Looker Studio 資料視覺化實戰班|GoogleAds x FB廣告 x GA流量數據

如何串接多種數位工具資訊?Looker Studio 資料視覺化實戰班|GoogleAds x FB廣告 x GA流量數據

Looker Studio除了可協助使用者監控網站流量、廣告成效、選擇匯入資源的管道之外,還可以將數據資料多平台整合、數據報表即時更新、數據範本可重複套用的效益,透過自動化系統,將數據全部匯入同一個報表平台,是企業不可或缺的重要工具。

輸入折扣碼 TC1270JIA 還可以額外獲得 NT$500 優惠喔。

和我們交流

加入我們的社群,裡面會有一些技術的內容、有趣的技術梗,以及職缺的分享,歡迎和我們一起討論。