如何使用jQuery在点击和鼠标hover上制作可滚动的div滚动

使用下面的标记,当我单击或将鼠标hover在“#scrollUp”或“#scrollDown”锚标记上时,如何向上或向下滚动“#content”div。 滚动应该是平滑的。 如果点击它应滚动特定数量(对于触摸设备)如果鼠标hover它可以滚动直到mouseout。

 #content { overflow:auto; height: 50px; /*could be whatever*/ }    
  • some content here
  • some content here
  • some content here
  • some content here
  • some content here
  • some content here

你可以使用jQuery的animate函数来实现clickmouseover的平滑滚动效果:

 var step = 25; var scrolling = false; // Wire up events for the 'scrollUp' link: $("#scrollUp").bind("click", function(event) { event.preventDefault(); // Animates the scrollTop property by the specified // step. $("#content").animate({ scrollTop: "-=" + step + "px" }); }).bind("mouseover", function(event) { scrolling = true; scrollContent("up"); }).bind("mouseout", function(event) { // Cancel scrolling continuously: scrolling = false; }); $("#scrollDown").bind("click", function(event) { event.preventDefault(); $("#content").animate({ scrollTop: "+=" + step + "px" }); }).bind("mouseover", function(event) { scrolling = true; scrollContent("down"); }).bind("mouseout", function(event) { scrolling = false; }); function scrollContent(direction) { var amount = (direction === "up" ? "-=1px" : "+=1px"); $("#content").animate({ scrollTop: amount }, 1, function() { if (scrolling) { // If we want to keep scrolling, call the scrollContent function again: scrollContent(direction); } }); } 

工作示例: http : //jsfiddle.net/andrewwhitaker/s5mgX/

(您必须禁用mouseovermouseout事件才能正确查看click事件处理程序的效果)

这个怎么运作:

  • 使用上面提到的animate函数在点击时平滑滚动指定的量。
  • 使用标志在链接的mouseover事件处理程序被调用时启用连续滚动,并在链接的mouseout事件处理程序时禁用滚动。
  • 调用scrollContent ,如果在动画完成后scrolling标志仍为true ,则再次以相同方向设置动画。 animate的回调函数参数允许我们在动画完成后执行操作。

尝试使用JavaScript而不是jQuery来完成此任务。 谷歌的functionscrollBy()window.scrollBy()