簡體   English   中英

如何使用jQuery在click和mouseover上創建可滾動的div滾動

[英]How to make a scrollable div scroll on click and mouseover using jQuery

使用下面的標記,當我單擊或懸停在“#scrollUp”或“#scrollDown”錨標記上時,如何向上或向下滾動“#content”div。 滾動應該是平滑的。 如果點擊它應滾動特定數量(對於觸摸設備)如果鼠標懸停它可以滾動直到mouseout。

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

你可以使用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來完成此任務。 谷歌的功能scrollBy()window.scrollBy()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM