简体   繁体   中英

Scroll Top Jump issue during offset top -150px

Please help me to resolve the following issue. I tried to implement smooth scroll when respective links are clicked. The issue am facing is the top portion of the section which is scrolled to is hidden behind the fixed header (which is of 150px height). Here is smooth scroll script am using. Not sure how to get this done. I tried adding -150px . But its not working properly. Please help.

$('.smoothscroll').on('click', function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top -150}, 'slow','swing').promise().done(function () {
            // check if menu is open
            if ($('body').hasClass('menu-is-open')) {
                $('.menu-toggle').trigger('click');
            }
            window.location.hash = target;
        });
    });

You can use pure JavaScript abilities to do your desire, jQuery make your codes dirty. see below code:

window.scroll({
   behavior: 'smooth',
   top: 0,
   left: 0
});

This code can scroll you to 0 offset of the top and 0 offset of the left coordinates, instead of the zeros you can set the offset of you to want.

You can make it as a function:

const smoothScroll = (topOffset, leftOffset) => {
    window.scroll({
        behavior: 'smooth',
        top: topOffset,
        left: leftOffset
    });
};

If you have other question, ask in comment and I will change or edit my answer for you.

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