jQuery Sortable List - scroll bar jumps up when sorting

后端 未结 13 1158
慢半拍i
慢半拍i 2020-12-24 12:28

I created a demo: http://pastebin.me/584b9a86d715c9ba85b7bebf0375e237

When the scroll bar is at the bottom and you drag items to sort them, it causes the scroll bar

13条回答
  •  佛祖请我去吃肉
    2020-12-24 13:22

    Carl M. Gregory explains the issue perfectly, but I think his solution is unnecessarily complicated.

    Setting list height to fixed value fixes the issue, but doing so at the moment of creating the list is way too early. You can use .mousedown() function to set the height right before the sorting starts. By this time any potential images are already loaded, so there is no need in checking their sizes.

    So the jump doesn't occur, but now please consider this: You have multiple connected list and they are arranged vertically. Now this happens:

    1. You start dragging from the upper list
    2. The upper list now has fixed height
    3. Move the item to the bottom list
    4. Bottom list nicely adjusts, because its' height is auto
    5. The upper list still has the same fixed height though it should be one item shorter

    So at some point, you should return its' height back to auto. When? On mouseup is too late (see https://jsfiddle.net/937vv4tx/1/), but it's okay, you can return the correct value almost immediately after the jump is no more a threat. Using the start() event

    Update: But you still want to set height to auto on .mouseup() because if you just click on item and don't start dragging, it still sets fixed height because the .mousedown() has already happened.

    $('.sortable').mousedown(function() {
        // set fixed height to prevent scroll jump
        // when dragging from bottom
        $(this).height($(this).height());
    }).mouseup(function () {
        // set height back to auto 
        // when user just clicked on item
        $(this).height('auto');
    }).sortable({
        connectWith: '.sortable',
        placeholder: 'placeholder',
        start: function() {
            // dragging is happening
            // and scroll jump was prevented,
            // we can set it back to auto
            $(this).height('auto');
        }
    });
    

    This code works perfectly for me.

提交回复
热议问题