0

Sorry if this is already out there somewhere, but I've been looking for a while and haven't found anything. I'd like to know if there's any way to, given the x and y coordinates/offset for an absolutely positioned element on a page, change that element into a relatively positioned element, but have it stay in the same visual spot, changing its location in the DOM. For example, given this html

<div id="divOne"></div>
<div id="divTwo"></div>
<div id="divThree"></div>

if divOne were positioned absolutely and its position happened to visually fall between divTwo and divThree, is there a way for me to convert its x,y position so I would be able to tell jQuery to place it after divOne and before divTwo in the DOM? I'm well versed in Javascript and jQuery, I'm just looking for a method I may not know about or for an answer from someone who may have come across this before.

4

1 回答 1

0

通过删除拖动的 div 的绝对定位,您必须将其标签放置在 dom 中的不同位置才能重新定位。

例如,如果您拖动#divOne 使其在#divTwo 和#divThree 之间视觉上移动,您应该做的是删除#divOne 的绝对定位并将其标签移动到其他两个div 之间:

<div id="divTwo"></div>
<div id="divOne"></div>
<div id="divThree"></div>

如果您有一个明确定义的网格,这将起作用。

如果我是你,我会做的就是为我想要重新排列的网格中的任何 div 提供一个标准类。例如,“可安排”类。当拖动端触发时,我将使用以下公式计算拖动的 div 必须放置在 dom 中的位置:

拖动的 div 应该移动到 dom 上的另一个位置。将会发生的是,拖动的 div 将取代现有的 div 并在其后“推动”现有的。例如,通过在#divTwo 和#divThree 之间拖动#divOne,#divOne 代替#divThree 并将其推到后面。假设当拖动的 div 位于将要被拖动的 div 占据的现有 div 上(我们将其命名为“pushedDiv”)时,用户停止拖动并释放左键,那么您所要做的就是识别 pushedDiv ,从 dom 中删除拖动的一个,将其放置在已识别的那个之前并使其位置相对。

为了了解哪个是 pushDiv,您可以使用以下例程:

//on drag end, where mouse has x and y coords:
var pushedDiv;
$(".arrangeable").each(function(index,value){
    var theoffset = $(this).offset();
    if(x >= theoffset .left && x <= theoffset .left + $(this).width() && y >= theoffset .top && y <= theoffset .top + $(this).height()){
         pushedDiv = $(this);
    }
});
// if pushedDiv is still null then the user didn't release the left click over a div of class "arrangeable". Else, the pushedDiv will be the one we are looking for
于 2013-07-11T20:36:11.780 回答