2012-11-03 33 views
9

請看看下面的小提琴:jQuery的排序保持容器邊界內

http://jsfiddle.net/ujdsu/

HTML,簡單的無序列表:

<ul class="sortable"> 
    <li>first item</li> 
    <li>second item</li> 
    <li>third item</li> 
    <li>fourth item</li> 
    <li>fifth item</li> 
</ul> 

的jQuery:

$(function() {  
    $(".sortable").sortable({ 
     axis: 'y' 
    }).disableSelection(); 
});​ 

CSS:

ul{ 
    margin:20px 0 0 20px; 
    border:1px solid #000; 
    width:70%; 
    overflow:hidden; 
    position:relative; 
} 
li{ 
    background:#ccc; 
    border-top:1px solid #000; 
    padding:10px 5px; 
    cursor:move; 
} 
li:first-child{ 
    border-top:0; 
} 

默認情況下,您可以拖動其容器外的項目。我已經通過在容器中添加「overflow:hidden」來解決這個問題,但是,您仍然可以將容器拖到容器外,只是不會看到外面的部分。請看下面的屏幕截圖:

enter image description here

我想要達到的目的是讓用戶無法在物品碰到容器的頂部或底部邊緣時進一步移動物件,因此您不會看到顯示在上面的截圖。理想情況下,「第三項」將達到最高點,不會再有任何進展。

感謝

回答

22

您需要通過containment選項:

$(function() {  
    $(".sortable").sortable({ 
     axis: 'y', 
     containment: "parent" 
    }).disableSelection(); 
});​ 

這裏是代碼的工作示例:

http://jsfiddle.net/VzpBq/

Sortable jQueryUI APIcontainment選項的定義

Def這是一個邊界框,可排序的項目被約束,而 拖動。

+1

美麗。謝謝福爾曼! – Sammy

+0

這個實現有一個小問題。如果我從頂部點擊第二個項目並將其拖出來,一切都很好,但是如果從底部點擊相同的第二個項目並拖動起來,它將返回到其初始位置,並且沒有任何內容會被排序! – armen

+2

@armen然後嘗試在可排序的初始化中將屬性'tolerance'設置爲值'pointer':$(「.sortable」).sortable({containment:'parent',tolerance:'pointer'}); – Ricardo