jquery sortable keep within container Boundary

北城以北 提交于 2019-12-23 07:29:24

问题


Please look at the fiddle below:

http://jsfiddle.net/ujdsu/

HTML, simple unordered list:

<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;
}

By Default you can drag an item outside its container. I've sort of fixed this by adding "overflow:hidden" to the container, however, you can still drag an item outside the container, you just wont see the part that's outside.. look at the screen shot below:

What I want to achieve is for the user to not be able to move the item any further as soon as it hits the top or bottom edge of the container, so you wouldn't see the result shown in the screenshot above. Ideally "third item" would hit the top edge and wouldn't move any further.

Thanks


回答1:


You need to pass the containment option:

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

Here is a working example with the code: http://jsfiddle.net/VzpBq/

Definition of the containment option from the Sortable jQueryUI API:

Defines a bounding box that the sortable items are contrained to while dragging.



来源:https://stackoverflow.com/questions/13204871/jquery-sortable-keep-within-container-boundary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!