vue与react当路由页面跳转时滚动位置不对的处理


在我们开发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]);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM