HTML + javascript implement a draggable list 一个可以拖拽交换顺序的列表

Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragover_event


<body>
    <style type="text/css">
        .draggable {
          text-align: center;
          background: red;
          width: 20px;
          height: 20px;
          margin: 2px;
        }
    </style>

    <div>
        <div class='draggable' id='1' draggable='true'>1</div>
        <div class='draggable' id='2' draggable='true'>2</div>
        <div class='draggable' id='3' draggable='true'>3</div>
        <div class='draggable' id='4' draggable='true'>4</div>
    </div>

    <script type="text/javascript">
        let dragging = null
        document.querySelectorAll('.draggable')
            .forEach(e => {
                e.addEventListener('dragstart', e=>{
                    dragging=e.target
                })
                e.addEventListener('dragenter', e=>{
                    e.preventDefault()
                    const target = e.target
                    const draggingId = parseInt(dragging.id)
                    const targetId = parseInt(target.id)

                    target.id = draggingId
                    dragging.id = targetId

                    if (targetId > draggingId) {
                        dragging.insertAdjacentElement('beforebegin', target)
                    } else {
                        dragging.insertAdjacentElement('afterend', target)
                    }
                })
                e.addEventListener('dragover', e=>{
                    e.preventDefault()
                })
                e.addEventListener('drop', e=>{
                    e.preventDefault()
                })
            })
    </script>
</body>

posted on 2023-04-01 15:59  明天有风吹  阅读(26)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园