Javascript 如何使用jQuery在单击和鼠标悬停时滚动可滚动的div

Javascript 如何使用jQuery在单击和鼠标悬停时滚动可滚动的div,javascript,jquery,scroll,Javascript,Jquery,Scroll,使用下面的标记,当我单击或将鼠标悬停在“#scroll up”或“#scroll down”锚标记上时,如何使“#content”div向上或向下滚动。滚动最好是平滑的。如果单击鼠标,它应该滚动特定数量(对于触摸设备),如果鼠标可以滚动到鼠标离开 <style> #content { overflow:auto; height: 50px; /*could be whatever*/ }

使用下面的标记,当我单击或将鼠标悬停在“#scroll up”或“#scroll down”锚标记上时,如何使“#content”div向上或向下滚动。滚动最好是平滑的。如果单击鼠标,它应该滚动特定数量(对于触摸设备),如果鼠标可以滚动到鼠标离开

 <style>  
         #content {
         overflow:auto;
         height: 50px; /*could be whatever*/
                 }
  </style>

<a id="scrollUp" href="#">up</a>
<a id="scrollDown" href="#">down</a>

<div id="wrapper">
 <div id="content">

  <ul>
    <li>some content here</li>
    <li>some content here</li>
    <li>some content here</li>
    <li>some content here</li>
    <li>some content here</li>
    <li>some content here</li>
  </ul>

 </div>
</div>

#内容{
溢出:自动;
高度:50px;/*可以是任何值*/
}
  • 这里有一些内容
  • 这里有一些内容
  • 这里有一些内容
  • 这里有一些内容
  • 这里有一些内容
  • 这里有一些内容

尝试使用JavaScript而不是jQuery来完成此任务。在
窗口中搜索函数
scrollBy()
。scrollBy()

您可以使用jQuery函数在
单击
鼠标悬停
上实现平滑的滚动效果:

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);
        }
    });
}
工作示例:

(您必须禁用
mouseover
mouseout
事件,才能正确查看
单击事件处理程序的效果)

工作原理:

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

Andrew-你太棒了。非常好的解释和解决方案。
scrollBy()
仅在窗口中可用。我想他是要求滚动一个div。