簡體   English   中英

導航欄固定頂部,可平滑滾動

[英]Smooth scroll with navbar fixed top

我有一個小問題。 我使用平滑滾動,完美...但是當我使用導航欄固定頂部時? 我的問題是當我單擊導航欄下的錨點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>

如何降低錨點?

我使用以下代碼進行平滑滾動:

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

資金在http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery上 如果您將$ target.offset()。top-導航欄的高度更改為80,則可以完成此操作。

下面的代碼對我來說很好。 沒有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