Next.js 在页面路由时保持滚动位置

Lee*_*nHo 6 javascript scroll-position next.js

我目前正在使用 Next.js 样板制作一个网站。

我的路由代码是这样的。(以下)

import Link from 'next/link'


<Link href={{ pathname: '/some-url', query: { param: something } }}>
  <div>
    <button type="button" onClick={handleClickMore}><span>+ More</span></button>
  </div>
</Link>
Run Code Online (Sandbox Code Playgroud)

当我点击它时,我<Button>不想移动滚动位置。但如您所知,当路由新页面时,它会移动到顶部。有没有人知道在加载新分页时保持滚动位置。

小智 14

<Link scroll={false} href="/"><a>Home</a></Link>
Run Code Online (Sandbox Code Playgroud)

scroll={false} 将禁用该特定链接的页面更改滚动到顶部。

参考:https : //github.com/zeit/next.js/issues/3950


小智 -13

You may disable the scrolling There are two examples bellow

.scrollDisabled {   
    position: fixed;
    margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
    width: 100%;
}
JS

var y_offsetWhenScrollDisabled=0;

function disableScrollOnBody(){
    y_offsetWhenScrollDisabled= $(window).scrollTop();
    $('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
    $('body').removeClass('scrollDisabled').css('margin-top', 0);
    $(window).scrollTop(y_offsetWhenScrollDisabled);
}



Another way 



.stop-scrolling {
  height: 100%;
  overflow: hidden;
}


$('body').addClass('stop-scrolling')
Run Code Online (Sandbox Code Playgroud)