javascript - 在靠近底部的地方拖动时在可移动的 DIV 内部滚动

标签 javascript jquery css drag-and-drop

我在一个可滚动的 div 中有多个可拖动的 div。当我将它们拖入可放置区域(这也是一个可滚动的 div)时,可放置的 DIV 不会向下滚动。只是页面在移动。 怎么说,只有可放置的 div 应该在拖动时滚动?

这是我当前用于使 div 可拖动的 jquery 代码

$(".drag_item").draggable({
        helper: 'clone',
        scroll: true, 
        drag: function( event, ui ) {
            $(this).css('z-index','100');
        }
    });

enter image description here

最佳答案

我想到了这个解决方案:

var direction = {};
var bound = {};
var scrolling = false;
var container = document.getElementById("container");

$('#table-container')
.on('dragstart', draggable, function(event, ui) {
  bound = {
    right : $(container).offset().left + $(container).width() - 50,
    left : $(container).offset().left + 50,
    top : $(container).offset().top + 50,
    bottom : $(container).offset().top + $(container).height() - 50
  };
})
.on('dragstop', draggable, function(event, ui) {
  direction = {};
})
.on('drag', draggable, function(event, ui) {
  direction.right = event.clientX - bound.right;
  direction.left = bound.left - event.clientX;
  direction.up = bound.top - event.clientY;
  direction.down = event.clientY - bound.bottom;

  if ((direction.right > 0 || direction.left > 0|| direction.up > 0 || direction.down > 0) && !scrolling) {
    scroll();
    scrolling = true;
  } else {
    scrolling = false;
  }
});

function scroll() {
  if (direction.right > 0) {
    container.scrollLeft = container.scrollLeft + (direction.right >> 1); //dividing by 2 to soften effect
  }
  if (direction.left > 0) {
    container.scrollLeft = container.scrollLeft - (direction.left >> 1);   
  }
  if (direction.down > 0) {
    container.scrollTop = container.scrollTop + (direction.down >> 1);
  }
  if (direction.up > 0) {
    container.scrollTop = container.scrollTop - (direction.up >> 1);
  }

  if (direction.right > 0 || direction.left > 0 || direction.up > 0 || direction.down > 0) {
    setTimeout(scroll, 100);
  }
}

关于javascript - 在靠近底部的地方拖动时在可移动的 DIV 内部滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545811/

相关文章:

javascript - YouTube API 和 playVideo 的噩梦

javascript - jQuery Deferred - 向 Deferred 合约添加回调

javascript - 禁用页面上的(大多数)事件?

css - JQuery 移动版 : Replace thumbnail with data element

css - 如何在 bootstrap 中使用 Lesser div

html - 将图像对齐到左浮动 div 的底部

javascript - 连接mongodb到 Node 报错

Javascript 属性为 NaN

javascript - Sails Js 中的动态数据库连接

javascript - 如何让Jquery可排序插件使用表格中的多行进行拖动