JQuery Sortable and automatic scrolling

后端 未结 9 2258
走了就别回头了
走了就别回头了 2021-02-05 10:02

I am trying to get JQuery Sortable to work but I have run into a slight usability problem.

The list that I am trying to sort is quite large (about 200 items). If the

9条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 10:20

    Scroll window when an item is dragged close to the top or bottom.

    I could not get any of the other answers working. Using Chrome and a sortable grid that needs to scroll vertically when an item is being dragged to the top or bottom edge of the window.

    NOTE: This only works for scrolling the entire window. This will not work if you have a scrollable section inside of the window and need to scroll that.

    I was able to get the following working flawlessly:

    var currentlyScrolling = false;
    
    var SCROLL_AREA_HEIGHT = 40; // Distance from window's top and bottom edge.
    
    $(".sortable").sortable({
        scroll: true,
    
        sort: function(event, ui) {
    
          if (currentlyScrolling) {
            return;
          }
    
          var windowHeight   = $(window).height();
          var mouseYPosition = event.clientY;
    
          if (mouseYPosition < SCROLL_AREA_HEIGHT) {
            currentlyScrolling = true;
    
            $('html, body').animate({
              scrollTop: "-=" + windowHeight / 2 + "px" // Scroll up half of window height.
            }, 
            400, // 400ms animation.
            function() {
              currentlyScrolling = false;
            });
    
          } else if (mouseYPosition > (windowHeight - SCROLL_AREA_HEIGHT)) {
    
            currentlyScrolling = true;
    
            $('html, body').animate({
              scrollTop: "+=" + windowHeight / 2 + "px" // Scroll down half of window height.
            }, 
            400, // 400ms animation.
            function() {
              currentlyScrolling = false;
            });
    
          }
        }
    });
    

    Coffeescript Version

    currentlyScrolling = false
    SCROLL_AREA_HEIGHT = 40
    
    sort: (event, ui) ->
    
      return if currentlyScrolling
    
      windowHeight = $( window ).height()
    
      mouseYPosition = event.clientY
    
      if mouseYPosition < SCROLL_AREA_HEIGHT # Scroll up.
        currentlyScrolling = true
        $( 'html, body' ).animate( { scrollTop: "-=" + windowHeight / 2 + "px" }, 400, () -> currentlyScrolling = false )
    
      else if mouseYPosition > ( windowHeight - SCROLL_AREA_HEIGHT ) # Scroll down.
        currentlyScrolling = true
        $( 'html, body' ).animate( { scrollTop: "+=" + windowHeight / 2 + "px" }, 400, () -> currentlyScrolling = false )
    

提交回复
热议问题