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

时间:2016-07-30 01:23:36

标签: javascript jquery smooth-scrolling

这是以前在此处回答的问题的扩展:See Prevoius Question

我有一些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);
}

});

1 个答案:

答案 0 :(得分:0)

无论何时滚动到元素,都必须按固定导航栏的高度向下滚动元素。同样,页面上的第一个元素需要一个边距或填充以偏移导航栏的高度。

由于这两个偏移都相同,因此您可以在设置第一个元素的偏移量的同时设置滚动偏移量。滚动到元素时,从顶部减去高度偏移量。即使滚动到顶部,这仍然有效。

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);
    });
});