问题
I'm having a hard time trying to 'lock' the depth of nested sortable elements, so that they can only sort 'up and down' among their direct siblings.
I thought I had it with this, but I can still 'pull' child items out of their parent and vice versa.
var $sort = $( '#outside-wrapper' ).sortable({
axis : 'y',
items : '.item',
start : function( event, ui ) {
// dynamically set the containment to the item's direct parent once started
$sort.sortable( 'option', 'containment', ui.item[0].parentNode );
}
});
Here's an example of the markup requirements;
<div class="item">
<div class="item"><!-- content --></div>
<div class="item">
<div class="item"><!-- content --></div>
<div class="item">
<div class="item"><!-- content --></div>
</div>
</div>
</div>
Appreciate any pointers!
回答1:
Well, many many thanks to jQuery UI: Only allow sortable within its own parent level, and not above or below.
The final result was;
sort.call( $( '#outside-wrapper' )[0] );
function sort() {
$( this )
.sortable( 'destroy' )
.sortable({ items : '> .item' })
.find( '> .item' )
.each( sort );
}
The destroy's in there, since I had to rebind whenever I added to the DOM. Seems a little recursively intensive, but as they say... it works.
UPDATE: IE (7 & 8) projectile vomited. Seemed the drag event was bubbling up, and all the parent nodes went with it, moving exponential distances from one another...
Yeah, nice to look at it. Not my cup of tea though. Fixed with handler: '> .handler'
i.e. don't use the sortable object as the handler!
回答2:
I'm going to add an answer, even though it's marked as answered:
There is a easier, less pretty solution. If you call the sortable on the children, they remain a group:
<div class="items">
<div class="one"> x </div>
<div class="one"> x </div>
<div class="one">
<div class="items">
<div class="one"> x </div>
<div class="one"> x </div>
<div class="one"> x </div>
</div>
</div>
</div>
In the code above, this will work:
$('div.items, div.items').sortable({/* ... */});
I've found this fiddle with similar code: http://jsfiddle.net/GMUbj/184/
来源:https://stackoverflow.com/questions/6447305/nested-sortable-elements-lock-depth