문제

I have a list containing different items that needs to be sortable. But there is an additional twist: certain elements are only allowed in specific positions in the list.

An example (please look at http://jsfiddle.net/pYL32/2/): There's a list containing elements foo, bar and baz that needs to be sortable; but the item foo is only allowed at the top or at the bottom.

So I'm looking for the following behaviour:

  1. When I start dragging foo downwards and I cross the space between bar and baz, then the placeholder should jump to the last position after baz. When I stop dragging, the foo item should be placed at the bottom of the list.

  2. When I start dragging baz upwards and I cross foo, then the placeholder should rest below foo. When I stop dragging, the baz item should be placed between foo and bar

Can I somehow achieve this by hooking into the sortable's change event that is triggered whenever positions in the list change? Is it possible to revert position changes in a callback to this event?

Or is there another solution to my problem (I would really like to stick with just the jQuery UI library so I'm not looking for solutions using other frameworks/libs)?

도움이 되었습니까?

해결책 2

Vickel's answer is solvin my problem almost completely. The only thing that is a bit "ugly" with his solution is that there is no visual feedback during dragging on whether the current position is valid or not. So I went for the following solution:

beforeStop: function(event, ui) {
  if(ui.placeholder.index() == 2) return false;
},
change: function(event, ui) {
  if(ui.placeholder.index() == 2) ui.placeholder.addClass('invalid-position');
  else ui.placeholder.removeClass('invalid-position');
}

With this solution I check the position of the placeholder every time it changes and I add a class invalid-position to the placeholder whenever it is in an invalid position and would be reverted if dropped there. Based on this invalid-position class I then style the placeholder to give visual feedback (e.g. with a red border or background when in an invalid position).

다른 팁

use the widget's beforeStop event, detect the position of the placeholder and cancel the event if undesired position

beforeStop: function( event, ui ) {
    if(ui.placeholder.index()==2)  return false;
}

here the updated jsfiddle, you cannot drag foo to position 2 anymore

I know this is not exactly what you asked, but I found it comes pretty close functionality wise

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top