15

我有 50 个 div,但在我的窗口中它只显示 25 个,我在这些 div 上拖放活动。所以如果我将我的第一个 div 拖到第 25 个 div 附近,它应该自动滚动以显示剩余的 div。我该怎么做在jQuery中?任何想法?

我正在使用Nestable不可拖动()

4

4 回答 4

11

这将需要根据您的特定用例进行一些微调,但它似乎工作得很好。

工作示例

$('.dd').nestable({ /* config options */
});

$(window).mousemove(function (e) {
    var x = $(window).innerHeight() - 50,
        y = $(window).scrollTop() + 50;
    if ($('.dd-dragel').offset().top > x) {
        //Down
        $('html, body').animate({
            scrollTop: 300 // adjust number of px to scroll down
        }, 600);
    }
    if ($('.dd-dragel').offset().top < y) {
        //Up
        $('html, body').animate({
            scrollTop: 0
        }, 600);
    } else {
        $('html, body').animate({

        });
    }
});

相关 API 文档:

于 2013-07-27T18:08:54.070 回答
2

如果你想知道窗口的底部,你可以检查

$(window).height()

$(window).scrollTop();

于 2013-07-27T12:06:16.133 回答
1

我知道这是一个老话题,但由于此功能一直处于待机状态,我只是改进了 apaul34208 的代码,希望对您有所帮助

$(window).mousemove(function (e) {
    if ($('.dd-dragel') && $('.dd-dragel').length > 0 && !$('html, body').is(':animated')) {
        var bottom = $(window).height() - 50,
            top = 50;

        if (e.clientY > bottom && ($(window).scrollTop() + $(window).height() < $(document).height() - 100)) {
            $('html, body').animate({
                scrollTop: $(window).scrollTop() + 300
            }, 600);
        }
        else if (e.clientY < top && $(window).scrollTop() > 0) {
            $('html, body').animate({
                scrollTop: $(window).scrollTop() - 300
            }, 600);
        } else {
            $('html, body').finish();
        }
    }
});
于 2015-06-08T14:33:54.883 回答
1

对 Mencey 的代码进行了一些改进。它可能需要注意的是,它基于每 16 毫秒触发一次的间隔,而不是 mousemove()。我不知道这可能会带来多大的负担,因此请随意增加毫秒数或在某个时候触发 clearInterval。这样做的好处是滚动是连续的,而不是像 1j01 指出的那样摆动鼠标。

您还可以更改speedzone变量,zone作为窗口顶部和底部的像素区域,您可以在其中拖动项目。当您靠近窗口的顶部或底部时,滚动速度会上升,因为它会比较鼠标位置与窗口实际边缘之间的距离,从而使用户可以控制滚动速度。

var mouseY;
var speed = 0.15;
var zone = 50; 

$(document).mousemove(function(e){
   mouseY = e.pageY - $(window).scrollTop();
}).mouseover();

var dragInterval = setInterval(function(){

  if ($('.dd-dragel') && $('.dd-dragel').length > 0 && !$('html, body').is(':animated')) {
    var bottom = $(window).height() - zone;

  if (mouseY > bottom && ($(window).scrollTop() + $(window).height() < $(document).height() - zone)) {
    $('html, body').animate({scrollTop:  $(window).scrollTop() + ((mouseY + zone - $(window).height()) * speed)},0);
  }
  else if (mouseY < zone && $(window).scrollTop() > 0) {
     $('html, body').animate({scrollTop: $(window).scrollTop() + ( (mouseY - zone) * speed) },0);

  } else {
     $('html, body').finish();
  }
  }
},16);
于 2018-05-30T16:24:25.153 回答