vue与react当路由页面跳转时滚动位置不对的处理
在我们开发react或者vue项目的时候会发现当切换路由进行页面跳转的时候如果在前一个页面将滚动条滚到了最下面然后进行跳转那么接下来的那个页面也会默认滚动在最下面。这个时候我们就需要处理一下。在处理之前我们首先需要知道原因在哪里:原因是因为虚拟dom的算法问题,导致不会更新scroll解决方法:在你的外层框架监听history.location.pathname的变化,只要变了那就将b...
·
在我们开发react或者vue项目的时候会发现当切换路由进行页面跳转的时候如果在前一个页面将滚动条滚到了最下面然后进行跳转那么接下来的那个页面也会默认滚动在最下面。这个时候我们就需要处理一下。
在处理之前我们首先需要知道原因在哪里:
原因是因为虚拟dom的算法问题,导致不会更新scroll
解决方法:
在你的外层框架监听history.location.pathname的变化,只要变了那就将body或者其他某元素的scrollTop设置为0。
具体代码【react + antd项目代码展示】:
useEffect(() => {
if (document) {
if (document?.documentElement || document?.body) {
document.documentElement.scrollTop = document.body.scrollTop = 0;
}
if (document.getElementsByClassName('antd-pro-layouts-basic-layout-layoutContent')?.[0]) { // 找你自己框架主体样式
document.getElementsByClassName('antd-pro-layouts-basic-layout-layoutContent')[0].scrollTop = 0;
}
}
}, [history?.location?.pathname]);
更多推荐
已为社区贡献16条内容
所有评论(0)