简体   繁体   中英

How to re-position element on 'enddrag'?

I was wondering how you would be able to use the 'enddrop' event listener to change the position of an element.

I tried using this:

document.addEventListener('dragend', e => { e.target.style.left = e.clientX; e.target.style.top = e.clientY; });

This works, but it's looks un-natural because the coordinates of the upper-left of the element are changed to the mouse position. So, if the user drags the element by the upper-left point it will work perfectly, but if you drag anywhere else on the element, it gives it a snappy effect because the upper-left corner will snap to the mouse's position.

Thanks!

I recently solved a similar problem:

follow the link: Prevent drop event when it's already have child element ? Drag and Drop

at the moment you start drag(dragstart) you calculate the top and left offset based on the element and mouse position and at the end drag(dragend) event you use this offset to adapt as needed.

let offset = [0, 0] // initial state offset x, y
function dragStart(ev) {
    // your code..
    offsetX = ev.target.offsetLeft - ev.clientX
        ev.target.offsetLeft - ev.clientX,
        ev.target.offsetTop - ev.clientY
    ]
}

Any doubt put the code that I can help you.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM