当鼠标使用jquery移动到页面底部时,如何自动滚动窗口

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

我正在使用Nestable而不是draggable()

这将需要一些微调,具体取决于您的具体用例,但它似乎工作得相当好。

工作实例

$('.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文档:

  • .mousemove()
  • .innerHeight()
  • .scrollTop()
  • .offset()
  • .animate()

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

 $(window).height() 

$(window).scrollTop() ;

我知道这是一个老话题,但由于这个function保持待机状态,我只是改进了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(); } } }); 

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);