列表拖拽排序功能
阿新 • • 發佈:2018-11-07
前幾天在做專案的時候,遇到一個表格裡邊的資料通過上下拖拽來改變其排序方式,後來通過一陣查詢,發現jquery-ui提供了sortable這個方法,甚是歡喜,在此便把我寫的小demo奉上:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>拖拽排序</title> <!-- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> --> <!-- <link rel="stylesheet" href="/resources/demos/style.css"> --> <style> #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; border: 1px solid red; } #sortable li { margin:0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; } #sortable li span { position: absolute; margin-left: -1.3em; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#sortable").sortable({ axis: "y", // y方向拖動 containment: "parent", // 約束範圍為父元素內部 cursor: "move", cursorAt: { left: 5 }, // disabled: true, distance: 5, update: updateHandle }); // $( "#sortable" ).disableSelection(); var arr = []; function updateHandle() { arr=[]; Array.prototype.slice.call($('ul li')).forEach(function (element, index) { arr.push(element.dataset.id) }); console.log(arr.join(',')); } }); </script> </head> <body> <ul id="sortable"> <li class="ui-state-default" data-id="1">Item 1</li> <li class="ui-state-default" data-id="2">Item 2</li> <li class="ui-state-default" data-id="3">Item 3</li> <li class="ui-state-default" data-id="4">Item 4</li> <li class="ui-state-default" data-id="5">Item 5</li> <li class="ui-state-default" data-id="6">Item 6</li> <li class="ui-state-default" data-id="7">Item 7</li> <li class="ui-state-default" data-id="8">Item 8</li> <li class="ui-state-default" data-id="9">Item 9</li> </ul> </body> </html>