简体   繁体   English

偏移顶部-150px期间的滚动顶部跳转问题

[英]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). 面临的问题是滚动到该部分的顶部隐藏在固定标题(高度为150px)的后面。 Here is smooth scroll script am using. 这是正在使用的平滑滚动脚本。 Not sure how to get this done. 不知道如何完成这项工作。 I tried adding -150px . 我尝试添加-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. 您可以使用纯JavaScript功能来实现您的愿望, jQuery使您的代码变得肮脏。 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. 此代码可以滚动你0顶部和偏移0左坐标偏移,而不是零,你可以设置抵消你想要的。

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. 如果您还有其他问题,请发表评论,我将为您更改或编辑答案。

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

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