js列表拖拽更换顺序(有序号可删除)

本文介绍了一个用于实现拖放排序功能的轻量级库Sortable.js。通过简单的HTML、CSS和JavaScript代码示例,展示了如何使用Sortable.js创建一个可拖动排序的列表,并提供了包括排序更新和删除项等功能的具体实现。

插件的中文网: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.jsjquery.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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值