引入jquery和插件sortable.js(可在官网下载);
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="js/jquery-sortable.js"></script>
html结构
<h3>点击下方拖拽排序</h3>
<ol class='example'>
</ol>
<button id="onList">获取</button>
css
<style>
body.dragging,
body.dragging * {
cursor: move !important;
}
.dragged {
position: absolute;
opacity: 0.5;
z-index: 2000;
}
ol.example li.placeholder {
position: relative;
}
ol.example li.placeholder:before {
position: absolute;
}
</style>
JS部分
思路:1存储一份后台数据
2获取拖拽过后的列表进行对比
3获取到哪些li顺序发生改变。
<script>
$(function () {
$("ol.example").sortable()
})
let arr = [{
id: 1,
cont: 1
}, {
id: 2,
cont: 2
}, {
id: 3,
cont: 3
}, {
id: 4,
cont: 5
}, {
id: 6,
cont: 6
},]
arr.forEach(item => {
let str = `<li id="${item.id}" cont="${item.cont}">${item.cont}</li>`;
$('.example').append(str)
});
let newArr = []
$('#onList').click(function () {
$('.example li').each(function (i) {
newArr.push({
id: arr[i].id,
cont: $(this).attr('cont')
})
})
let list = [];
for (let j in newArr) {
for (let i in arr) {
if (newArr[j].id == arr[i].id) {
if (newArr[j].cont != arr[i].cont) {
list.push({
id: newArr[j].id,
cont: newArr[j].cont
})
}
}
}
}
console.log(list);
})
</script>