Forcing an item to remain in place in a jQuery UI Sortable list

前端 未结 3 1245
灰色年华
灰色年华 2020-12-31 07:05

I\'ve set up a jQuery sortable list but I need to be able to keep some items in the sortable \'fixed\' in place and for the other items to sort around them. I thought that t

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 07:43

    I managed to do this by modifying jitters code a bit, and attach it to the "change" event rather than the "stop". I did it by looking how the index changes when dragging an item around and set up some conditionals. It also works with multiple fixed elements. The "lockto" variable defines the positon of the fixed element, and the fixed element should be in this position initially. You could probably rewrite this and wrap it in a function so you don't need to manually set the "lockto" variable for all fixed elements.

    $("#sortable").sortable({
        "cancel":"li.static",
        "change":function(event,ui) {
            var lockto = 6;
            var thisindex = $(ui.helper).index(fixed);         
            var fixed = $("#static-"+lockto);           
            var index = $("#sortable li").index(fixed);
            var targetindex = lockto+1;
            if(index !== targetindex) {         
                if(index > targetindex ) {
                    fixed.prev().insertAfter(fixed); //move it up by one position
                } else if(index==(targetindex-1) && thisindex>targetindex) {
                    //don't move it at all
                } else {
                    fixed.next().insertBefore(fixed); //move it down by one position
                }
            } else if(index==targetindex && thisindex>targetindex) {
                fixed.prev().insertAfter(fixed); //move it up by one position
            }       
        }
    });
    

提交回复
热议问题