在我們開發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]);