【问题标题】:How to make a scrollable div scroll on click and mouseover using jQuery如何使用 jQuery 在单击和鼠标悬停时使可滚动的 div 滚动
【发布时间】:2010-12-31 19:08:28
【问题描述】:

使用下面的标记,当我单击或悬停在“#scrollUp”或“#scrollDown”锚标记上时,如何让“#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>

【问题讨论】:

    标签: javascript jquery scroll


    【解决方案1】:

    你可以使用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 的回调函数参数允许我们在动画完成后采取行动。

    【讨论】:

    • 安德鲁 - 你摇滚。很好的解释和解决方案。
    【解决方案2】:

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

    【讨论】:

    • scrollBy() 仅在窗口中可用。我认为他要求滚动一个 div。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2011-11-26
    • 1970-01-01
    • 2019-03-03
    • 2010-12-12
    相关资源
    最近更新 更多