插件的中文网:http://www.sortablejs.com/index.html
下载地址:https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js
效果
代码
HTML
- 可以拖拽的是id为
example1
的标签里面的元素 span
标签里面的是序号i
标签是关闭按钮
<div>
<h4>简单列表拖拽</h4>
<div>
<div id="example1" class="list-group">
<div class="list-group-item"><span>1-</span>Item 1<i>x</i></div>
<div class="list-group-item"><span>2-</span>Item 2<i>x</i></div>
<div class="list-group-item"><span>3-</span>Item 3<i>x</i></div>
<div class="list-group-item"><span>4-</span>Item 4<i>x</i></div>
<div class="list-group-item"><span>5-</span>Item 5<i>x</i></div>
<div class="list-group-item"><span>6-</span>Item 6<i>x</i></div>
</div>
</div>
</div>
CSS
blue-background-class
是移动时该标签的样式,这里设置移动时背景颜色为天蓝色
.list-group {
display: flex;
flex-direction: column;
}
.list-group-item {
display: block;
position: relative;
padding: .75rem 1.25rem;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid rgba(0,0,0,.125);
}
.list-group-item:first-child {
border-top-left-radius: .25rem;
border-top-right-radius: .25rem;
}
.blue-background-class {
background: skyblue;
}
.list-group-item i {
display: inline-block;
float: right;
width: 50px;
height: 50px;
line-height: 50px;
color: red;
cursor: pointer;
}
JS
- 别忘了引入
Sortable.min.js
和jquery.min.js
哦 onUpdate
是列表内元素顺序更新的时候触发的,此时可以看到你挪动的元素的最初和最后的下标,然后更改一下整体的序号点击删除
后删除当前的元素,再重新排列下序号就好- 如果想往里面
添加元素
,用append()也可以,然后同样的,需要重新排列下序号
<script>
//使用Sortable插件
new Sortable(example1, {
animation: 150,
ghostClass: 'blue-background-class',
onUpdate: function(evt) {
console.log("evt.oldIndex : "+evt.oldIndex);
console.log("evt.newIndex : "+evt.newIndex);
reset();
}
});
//点击删除按钮
$('.list-group-item i').click(function() {
$(this).parents('.list-group-item').remove();
reset();
})
//重新排序(前面的序号)
function reset() {
for(var i = 0 ;i <$('.list-group-item').length;i++){
$('.list-group-item:nth('+i+')').find('span').text(i+1+'-');
}
}
</script>