简体   繁体   English

使用按钮添加偏移以使用导航栏平滑滚动

[英]Add offset to smooth scroll with a navbar using buttons

Hello I tried to look up multiple solutions like I tried target:before for example but none of them really worked.您好,我尝试查找多个解决方案,例如我尝试过的target:before ,但它们都没有真正起作用。 My idea is to have a smooth scroll with an offset of -100px so that my fixed header is not blocking the content of the section.我的想法是平滑滚动,偏移量为 -100px,这样我固定的 header 就不会阻塞该部分的内容。 I found this solution which is using a href as a reference.我找到了这个使用a href作为参考的解决方案。

now is it possible to change that reference to button with the id "content"?现在是否可以更改对 ID 为“内容”的button的引用?

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

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

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

rest of my code:我的代码 rest:

 html { scroll-behavior: smooth; } * { margin: 0;important: padding; 0: font-family; helvetica: } body { height; 300vh: } #wrap { position; absolute: top; 400px: } #navbar { text-align; center: width; 100%: color; white: z-index; 999: transition. 0;3s: background-color; darkgray: position; fixed; }
 <html> <nav id="navwrapper"> <script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script src="javascript/navbar fixed.js"></script> <div id="navbar" class="navbar navbar-dark bg-primary navbar-fixed-top selectSection"> <h1 id="titel">HEADLINE</h1> <ul> <li class="nav-item"><button onclick="location.href='#wrap'" type="button" data-number="1" class="active navb">content1</button></li> </ul> </div> </nav> <div id="wrap" class="contentSection wrapper"> <section id="content1" class="content" data-number="1"> <div> content 1 </div> </section>

Okay.好的。 After googling even more I found this codepen using scroll-margin-top:;在谷歌搜索更多之后,我使用scroll-margin-top:;找到了这个代码笔 which worked in my case!在我的情况下有效!

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

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