简体   繁体   English

导航栏固定顶部,可平滑滚动

[英]Smooth scroll with navbar fixed top

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. 我的问题是当我单击导航栏下的锚点div链接时。 The navbar have height 154px and the code are simplyfy to this: 导航栏的高度为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? 如何降低锚点?

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 . 资金在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. 如果您将$ target.offset()。top-导航栏的高度更改为80,则可以完成此操作。

The code below works fine for me. 下面的代码对我来说很好。 No jquery, pure JS using scrollby. 没有jQuery,使用scrollby的纯JS。

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

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

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