Jquery sortable 'change' event element position

后端 未结 5 2071
生来不讨喜
生来不讨喜 2020-11-30 00:23

Is there way to get current position of helper being dragged on over new position ?

$(\"#sortable\").sortable({
        start: function (event, ui) {
                


        
5条回答
  •  长情又很酷
    2020-11-30 00:55

    If anyone is interested in a sortable list with a changing index per listitem (1st, 2nd, 3th etc...:

    http://jsfiddle.net/aph0c1rL/1/

    $(".sortable").sortable(
    {
      handle:         '.handle'
    , placeholder:    'sort-placeholder'
    , forcePlaceholderSize: true
    , start: function( e, ui )
    {
        ui.item.data( 'start-pos', ui.item.index()+1 );
    }
    , change: function( e, ui )
      {
          var seq
          , startPos = ui.item.data( 'start-pos' )
          , $index
          , correction
          ;
    
          // if startPos < placeholder pos, we go from top to bottom
          // else startPos > placeholder pos, we go from bottom to top and we need to correct the index with +1
          //
          correction = startPos <= ui.placeholder.index() ? 0 : 1;
    
          ui.item.parent().find( 'li.prize').each( function( idx, el )
          {
            var $this = $( el )
            , $index = $this.index()
            ;
    
            // correction 0 means moving top to bottom, correction 1 means bottom to top
            //
            if ( ( $index+1 >= startPos && correction === 0) || ($index+1 <= startPos && correction === 1 ) )
            {
              $index = $index + correction;
              $this.find( '.ordinal-position').text( $index + ordinalSuffix( $index ) );
            }
    
          });
    
          // handle dragged item separatelly
          seq = ui.item.parent().find( 'li.sort-placeholder').index() + correction;
          ui.item.find( '.ordinal-position' ).text( seq + ordinalSuffix( seq ) );
    } );
    
    // this function adds the correct ordinal suffix to the provide number
    function ordinalSuffix( number )
    {
      var suffix = '';
    
      if ( number / 10 % 10 === 1 )
      {
        suffix = "th";
      }
      else if ( number > 0 )
      {
    
        switch( number % 10 )
        {
          case 1:
            suffix = "st";
            break;
          case 2:
            suffix = "nd";
            break;
          case 3:
            suffix = "rd";
            break;
          default:
            suffix = "th";
            break;
        }
      }
      return suffix;
    }
    

    Your markup can look like this:

    • 1st A header
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    • 2nd A header
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    • etc....

提交回复
热议问题