簡體   English   中英

jQuery平滑滾動以錨定

[英]jQuery smooth scroll to anchor

我使用jQuery mousewheel擴展編寫了一個相當簡單的平滑滾動功能,但以前沒有使用$.mousewheel經驗,所以遇到了一個問題。

基本上,一旦south delta被調用,我就使用scrollTop調用一個$.animate函數到.anchor

HTML (簡化問題):

<div id="static-section" class="anchor"></div> <!-- width: 100%; height: 258px -->
<div id="alt-section" class="anchor"></div> <!-- width: 100%; height: 346px -->

jQuery的

$(document).ready(function() {
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("South: " + delta);
            // ANIMATE TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $(".anchor").offset().top}, "slow");
        }

        return false;
    });
});

所以:我的問題是,它只動畫到.anchor第一個實例(這將是#static-section ),我嘗試做scrollTop: $(".anchor").next().top顯然不起作用,盡管沒有出現錯誤,但它仍然僅動畫到第一個實例。 我的第一個猜測是使用for循環,我嘗試了一下,但是它沒有用(也沒有錯誤。)我以前從未真正使用過for循環,所以我不確定是否還是我做的是正確的 任何幫助將非常感激!

注意:jsFiddle(使用與我的網站相同的代碼)無法描繪出我已經完成的相同事情,因此沒有實時演示可用。 如果你們需要,我會根據要求提供URL。 :-)

這樣的事情將逐步通過.anchor標簽:

$(document).ready(function() {
    var $anchor = $('.anchor');
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("South: " + delta);
            // ANIMATE TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $anchor.offset().top}, "slow");
            $anchor = $anchor.next('.anchor');
        }

        return false;
    });
});

暫無
暫無

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

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