简体   繁体   中英

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. 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. I found this solution which is using a href as a reference.

now is it possible to change that reference to button with the id "content"?

$('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:

 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:; which worked in my case!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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