javascript 导航栏固定顶部的平滑滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19127212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:28:21  来源:igfitidea点击:

Smooth scroll with navbar fixed top

javascripthtml

提问by wario

i have a little question. I use smooth-scroll,its perfect... but when i use a navbar fixed top? My problem is when i click on link the anchor div its under the navbar. The navbar have height 154px and the code are simplyfy to this:

我有一个小问题。我使用平滑滚动,它完美......但是当我使用导航栏固定顶部时?我的问题是当我单击导航栏下方的锚点 div 链接时。导航栏的高度为 154px,代码很简单:

<header id="navbar" style="position: fixed; right: 0; left: 0; z-index: 1; height: 154px;">
    <a href="#anch1">Anchor 1</a>
    <a href="#anch2">Anchor 2</a>
</header>
<div id="anch1">...</div>
<div id="anch2">...</div>

how can I lower my anchor anchor point?

我怎样才能降低我的锚点?

回答by Olèp

I use this code for smooth scrolling:

我使用此代码进行平滑滚动:

$(document).ready(function () {
     $('a[href^="#"]').on('click', function (e) {
         e.preventDefault();

         var target = this.hash,
             $target = $(target);

         $('html, body').stop().animate({
             'scrollTop': $target.offset().top - 80
         }, 900, 'swing', function () {
             window.location.hash = target;
         });
     });
 });

fund on http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery. If you change the $target.offset().top - 80 with the height of your navbar you do the trick.

http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery 上的基金。如果您将 $target.offset().top - 80 更改为导航栏的高度,您就可以做到。

回答by danielarend

The code below works fine for me. No jquery, pure JS using scrollby.

下面的代码对我来说很好用。没有 jquery,纯 JS 使用 scrollby。

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            var node = document.querySelector(this.getAttribute('href'));
            let item = node;
            //this is the parent container, overflow wrapper
            let wrapper = document.querySelector('#wr-page');
            let count = item.offsetTop - wrapper.scrollTop ; 
            wrapper.scrollBy({top: count, left: 0, behavior: 'smooth'})
        });
    });