简体   繁体   English

如何滚动到部分但与顶部保持距离?

[英]How to scroll to section but keeping a distance from top?

I am using the following code to have a smooth scroll to section when we click a navigation menu item:当我们单击导航菜单项时,我使用以下代码平滑滚动到部分:

// handle links with @href started with '#' only
    $(document).on('click', 'a[href^="#"]', function(e) {
        // target element id
        var id = $(this).attr('href');

        // target element
        var $id = $(id);
        if ($id.length === 0) {
            return;
        }

        // prevent standard hash navigation (avoid blinking in IE)
        e.preventDefault();

        // top position relative to the document
        var pos = $id.offset().top;

        // animated top scrolling
        $('body, html').animate({scrollTop: pos}, 2000);
    });

However, I needed to put the header on position fixed, with a height of 90px and now when we scroll to the section, the beginning of the section is hidden behind the section.但是,我需要将标题放在固定的位置,高度为 90 像素,现在当我们滚动到该部分时,该部分的开头隐藏在该部分的后面。 Is it possible to keep my code and include for example a certain distance from the top?是否可以保留我的代码并包括例如距顶部一定的距离?

I tried to put a parameter on the offset method but it didn't work:我试图在 offset 方法上放一个参数,但没有用:

// handle links with @href started with '#' only
    $(document).on('click', 'a[href^="#"]', function(e) {
        // target element id
        var id = $(this).attr('href');

        // target element
        var $id = $(id);
        if ($id.length === 0) {
            return;
        }

        // prevent standard hash navigation (avoid blinking in IE)
        e.preventDefault();

        // top position relative to the document
        var pos = $id.offset(top:120).top;

        // animated top scrolling
        $('body, html').animate({scrollTop: pos}, 2000);
    });

Am I doing something wrong?难道我做错了什么?

var pos = $id.offset().top - 90;

是你的意思吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM