0

I have a generic HTML like this

<div>
    <span>Item 1</span>
    <span>Item 2</span>
    <span>Item 3</span>
    <span>Item 4</span>
</div>

And I need to implement a drag-to-change-order, being able to drag each item to change the order, like you can drag an image in a text editor and drop it between words, similar to how you you can do in Mail on ios or in the Mac Dock, but with text.

Like this: http://img5.imageshack.us/img5/1921/v57sibdzorpefuaqozisso.mp4

enter image description here

When a user drag something and change the order, I need the actual DOM to be in that order, and not just appear on the screen like when you do with position:absolute.

The first idea I had is to lift the element to position absolute, computing the coordinates, and when you drop, calculate where it should be relative to other elements and then position:relative back.

But I'm not sure if it's a good approach, and the implementation is not quite simple. And it's not what I would consider a elegant solution, and I'm concerned about it turning jerky.

I rather like vanilla javascript then jquery, but it can help me to implement my own.

I already implemented drag a and drop in javascript but for absolute positioned elements and it doesn't work on relative positioned elements.

I'm looking forward ideas.

http://jsfiddle.net/Victornpb/BWU3m/

4

1 回答 1

0

尚不清楚您希望可拖动的行为如何,因为您的图像暗示了一件事,而您的小提琴的工作方式不同(absolute您所说的带有元素的小提琴)。我在这里假设您希望能够像在图像中一样在文档中拖动它们。

相对定位元素和绝对定位元素之间存在一些差异。两者都取决于它们offsetParent(不一定parentNode),但是在relative元素上,上/左偏移始终为 0(或元素相对于自身的距离),除非您指定不同的值。在absolute元素上,左/上偏移是元素相对于offsetParent上/左边缘的距离。

因此,因为您所有的SPANs 都从left:0,top:0偏移量开始(如果我们不计算边距等),offsetParent因此在计算需要应用的左/上值时,您需要考虑元素的大小和原始偏移量,这可能是消极的。

初始化时,将其存储在originalOffset某处以供以后访问。

x应该:

(clientX - originalOffset - width)

然后确保x

(-originalOffset) .. (offsetParentWidth - width - originalOffset)

相同y,但改变轴。

要考虑的另一件事是内联元素没有clientWidth/Height.

这是我上面提到的更改的小提琴。如果您希望将拖动包含在 DIV 中,只需将 DIV 设为offsetParent.

于 2013-06-24T18:35:19.467 回答