【问题标题】:Vanilla JavaScript Drag And Drop - clone elementVanilla JavaScript 拖放 - 克隆元素
【发布时间】:2020-09-13 21:13:05
【问题描述】:

如何编辑这段 Javascript 代码以拖动元素并在原始容器中保留副本?

...

containers.forEach(container => {
    container.addEventListener('dragover', e => {
        e.preventDefault()
        const afterElement = getDragAfterElement(container, e.clientY)
        const draggable = document.querySelector('.dragging')
        if (afterElement == null) {
            container.appendChild(draggable)
        } else {
            container.insertBefore(draggable, afterElement)
        }
    })
})

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]

    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect()
        const offset = y - box.top - box.height / 2
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child }
        } else {
            return closest
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element
}

一切正常,我只需要留下一份已删除元素的副本。

【问题讨论】:

    标签: javascript html css drag-and-drop dom-events


    【解决方案1】:

    因为这个功能,它不会工作:

        function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
    
        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect()
            const offset = y - box.top - box.height / 2
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child }
            } else {
                return closest
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element
    }
    

    试试别的。

    【讨论】:

    • 请解释为什么“它不会因为这个功能而工作”,并提出一个可能的替代方案,而不是“尝试其他东西”。否则,这不是一个有效的答案。
    猜你喜欢
    • 2012-05-19
    • 2013-03-08
    • 1970-01-01
    • 2011-10-18
    • 2014-11-14
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多