簡體   English   中英

jQuery平滑滾動到頂部並按ID錨定(帶有偏移)

[英]jQuery Smooth Scroll to Top AND to Anchor by ID (with Offset)

這是先前在此處回答的問題的擴展: 請參閱Prevoius問題

我有一些jQuery,它既向頂部函數添加了平滑滾動,又向頁面上找到的所有錨添加了平滑滾動。

現在,我只需要向固定滾動添加一個偏移量(110px)即可解決固定的標題,而不會弄亂滾動到頂部的功能。

這是現有的代碼:

// Add To Top Button + Smooth Scroll to Anchors functionality
jQuery(document).ready(function($){
    // Scroll (in pixels) after which the "To Top" link is shown
    var offset = 700,
    //Scroll (in pixels) after which the "back to top" link opacity is reduced
    offset_opacity = 1200,
    //Duration of the top scrolling animation (in ms)
    scroll_top_duration = 700,
    //Get the "To Top" link
    $back_to_top = $('.to-top');

//Visible or not "To Top" link
$(window).scroll(function(){
    ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('top-is-visible') : $back_to_top.removeClass('top-is-visible top-fade-out');
    if( $(this).scrollTop() > offset_opacity ) { 
        $back_to_top.addClass('top-fade-out');
    }
});

//Smooth scroll to top
$back_to_top.on('click', function(event) {
    event.preventDefault();
    targetedScroll();
});

// example of smooth scroll to h2#anchor-name
$('#some-button').on('click', function(event) {
    event.preventDefault();
    targetedScroll('anchor-name');
});

// bind smooth scroll to any anchor on the page
$('a[href^="#"]').on('click', function(event) {
    event.preventDefault();
    targetedScroll($(this).attr('href').substr(1));
});

// scrolling function
function targetedScroll(id) {
    // scrollTop is either the top offset of the element whose id is passed, or 0
    var scrollTop = id ? $('#' + id).offset().top : 0;

    $('body,html').animate({
        scrollTop: scrollTop,
    }, scroll_top_duration);
}

});

每次滾動到某個元素時,都必須向下滾動該元素,使其比固定導航欄的高度低。 類似地,頁面上的第一個元素需要一個邊距或填充以抵消導航欄的高度。

由於這兩個偏移量都相同,因此可以在設置第一個元素的偏移量的同時設置滾動偏移量。 滾動到某個元素時,請從頂部高度減去偏移量。 即使滾動到頂部,此操作仍然有效。

jQuery(document).ready(function($) {
    var offset = $("nav").height();
    $("body").css("padding-top", offset + "px");
    $('a[href^="#"]').click(function(event) {
        event.preventDefault();
        var scrollY = $(this.href).offset().top;
        $('html, body').animate({
            scrollTop: scrollY - offset
        }, 2000);
    });
});

暫無
暫無

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

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