2012-01-08 72 views
1

我想允许拖放式重新排序类似photoshop的图层。如何通过拖放重新排列DOM中的画布元素?

假设我在第3个画布元素与IDS的a,b和c:

<canvas id="a"></canvas> 
<canvas id="b"></canvas> 
<canvas id="c"></canvas> 

c是“上顶”层,因为它是最近定义的,并且它们在顶部绝对定位彼此的;我如何重新排列元素到顺序:c,a,b,其中c现在在其他层之后?

<canvas id="c"></canvas> 
<canvas id="a"></canvas> 
<canvas id="b"></canvas> 

我想通过检测像这样的列表中拖动和拖放排序触发排序:

<ul id="layers"> 
    <li>Layer C</li> 
    <li>Layer B</li> 
    <li>Layer A</li> 
</ul> 

我大概可以使用jQuery UI的排序,以让列表的重新排序。使画布DOM顺序反映列表顺序的最简单方法是什么? (镜像有些相反,因为C on-top的列表映射到C上的画布。

回答

0

我相信你必须改变画布的z顺序而不是改变它们的顺序,或者我错误的反正,我建议是这样的:?

$("#layers").sortable({ 
    update: function(event, ui) { 
     $("canvas").detach(); // Removes all canvases 
     $("#layers li").each(function() { 
      // Reinsert them in the same order of your list items 
      $("#" + $(this).data("canvas")).appendTo(whereYourCanvasesWere); 
     }); 
    } 
}).disableSelection(); 

而在你的HTML:

<ul id="layers"> 
    <li data-canvas="c">Layer C</li> 
    <li data-canvas="b">Layer B</li> 
    <li data-canvas="a">Layer A</li> 
</ul> 

编辑:哦,如果你要反转它们被放置的顺序,只需使用prependTo而不是appendTo

+0

是的,重新排序z-index可能是最有效的方法,而不是重新安排dom来强制z索引更改。 – Homan 2012-01-08 18:16:05

1

调整z分数绝对是最好的选择。我用一种风格来处理我关心的所有元素。以下是我最近的一个项目的一些片段。

事情是这样的:

// brings the focus of the selected table on the canvas to the front 
function adjustFocus(event, ui) { 
    // clear any old focuses 
    $("#table-canvas").find(".table-view").each(function (index) { 
     $(this).removeClass("table-view-focus"); 
    }); 

    // add the focus to the current table 
    $(this).addClass("table-view-focus"); 
} 

类很简单:

.table-view-focus { z-index: 10; } 

调整焦距被称为用于拖动开始事件:

// make this view draggable 
     tableView.draggable({ 
      containment: "#table-canvas", 
      handle: "h3", 
      start: adjustFocus, 
      drag: tableViewDrag 
     });