js 原生拖拽排序功能 简单实现

拖拽排序功能还是挺常见的, 涉及到的api 还是挺多的,这里笔记记录一下以免忘记找不到了!
老规矩先上效果图

html部分

html 复制代码
 <div class="list-box">
        <div draggable="true" class="item">1</div>
        <div draggable="true" class="item">2</div>
        <div draggable="true" class="item">3</div>
        <div draggable="true" class="item">4</div>
        <div draggable="true" class="item">5</div>
        <div draggable="true" class="item">6</div>
    </div>

js 部分

js 复制代码
 <script>
        const list = document.querySelector('.list-box');
        let sourceNode;
        // 开始 拖拽
        list.ondragstart = (e) => {
            setTimeout(() => {
                e.target.classList.add('moving');
            }, 0)
            sourceNode = e.target
        };
        // 禁止元素在列表上方释放
        list.ondragover = (e) => {
            e.preventDefault();
        };
        // 拖拽进入
        list.ondragenter = (e) => {
            // 阻止默认行为
            e.preventDefault();
            // 排除 拖拽到外面 和 拖拽原本的位置
            if (e.target == list || e.target == sourceNode) return;
            const chidList = [...list.children]
            // 获取拖拽元素的下标
            const sourceIndex = chidList.indexOf(sourceNode);
            // 进入的元素下标
            const targetIndex = chidList.indexOf(e.target);
            if (sourceIndex < targetIndex) {
                // 将拖拽元素放在当前元素下方
                list.insertBefore(sourceNode, e.target.nextElementSibling)
            } else {
                // 将拖拽元素放在当前元素上方
                list.insertBefore(sourceNode, e.target)
            }
        };
        // 拖动结束移除默认样式
        list.ondragend = () => {
            sourceNode.classList.remove('moving')
        } 
    </script>

css 部分 这个图拽动画 要是相弄得好看还是有难度的 ,我就随便写了点样式

css 复制代码
<style>
        .list-box {
            list-style: none;
            width: 500px;
            margin: 0 auto;
            /* line-height: 30px; */
        }

        .item {
            background: aquamarine;
            height: 40px;
            line-height: 40px;
            border-radius: 4px;
            margin-bottom: 10px;
            user-select: none;
            transition: background-color 0.3s ease;
        }

        .item.moving {
            background: transparent;
            color: transparent;
            border: 1px dashed #ccc;
            transition: none;
        }
    </style>
相关推荐
程序员拂雨13 分钟前
Angular 知识框架
前端·javascript·angular.js
GoodStudyAndDayDayUp43 分钟前
gitlab+portainer 实现Ruoyi Vue前端CI/CD
前端·vue.js·gitlab
程序员阿明1 小时前
vite运行只能访问localhost解决办法
前端·vue
前端 贾公子1 小时前
uniapp -- 验证码倒计时按钮组件
前端·vue.js·uni-app
zhengddzz1 小时前
从卡顿到丝滑:JavaScript性能优化实战秘籍
开发语言·javascript·性能优化
淡笑沐白1 小时前
AJAX技术全解析:从基础到最佳实践
前端·ajax
Go_going_1 小时前
ajax,Promise 和 fetch
javascript·ajax·okhttp
龙正哲1 小时前
如何在Firefox火狐浏览器里-安装梦精灵AI提示词管理工具
前端·firefox
徐徐同学1 小时前
轻量级Web画板Paint Board如何本地部署与随时随地在线绘画分享
前端
LuckyLay2 小时前
Vue百日学习计划Day4-8——Gemini版
前端·vue.js·学习