前端滾動錨點三個常用方案(點擊后頁面滾動到指定位置)
三個常用方案:
1.scrollintoView
把調(diào)用該方法的元素滾動到屏幕的指定位置,中間,底部,或者頂部
優(yōu)點:方便,只需要獲取元素然后調(diào)用
缺點:不好精確控制,只能讓元素指定滾動到中間,頂部,底部,沒法設(shè)置偏移
block可以設(shè)置為center,end,start等來控制在頁面顯示的位置。
注意的就是
<script setup> import {onMounted, ref } from 'vue' import {useRoute }from 'vue-router' const { query }= useRoute(); const target = query.target onMounted(()=>{ document.getElementById(target)?.scrollIntoView({ block:'center' }) }) </script> <template> <button>美妝</button> <button>數(shù)碼</button> <button>美食</button> <button>家居</button> <button>黃金</button> <div class="home" id="home"> // 五個樓層 <div class="part" id="part1">美妝</div> <div class="part" id="part2">數(shù)碼</div> <div class="part" id="part3">美食</div> <div class="part" id="part4">家居</div> <div class="part" id="part5">黃金</div> </div> </template> <style> .home { width: 1000px; margin: 0 auto; height: 90vh; overflow-y: scroll; } .part { margin-top: 20px; border: 1px solid red; height: 600px; } .needData { height: 600px; } </style>
2.scrollTo
把可滾動元素滾動到指定x,y坐標(biāo)優(yōu)點:可以精確控制到具體多少px
缺點:得先獲取到x,y坐標(biāo)
需要注意的是,這個方法的調(diào)用者并不是要看到的元素,而是可滾動的元素。像方法一,調(diào)用scrollintoView方法的是五個樓層本身,但是如果是調(diào)
用scrollTo的話是調(diào)用他們的父級元素(id="home"的div盒子)它才是可滾動的元素.
<script setup> import {onMounted, ref } from 'vue' import {useRoute }from 'vue-router' const { query }= useRoute(); const target = query.target onMounted(()=>{ const targetDom = document.getElementById(target); const targetRect = targetDom.getBoundingClientRect(); document.getElementById(home)?.scrollTo(targetRect.x, targetRect.y - 100); }) </script> <template> <button>美妝</button> <button>數(shù)碼</button> <button>美食</button> <button>家居</button> <button>黃金</button> <div class="home" id="home"> <div class="part" id="part1">美妝</div> <div class="part" id="part2">數(shù)碼</div> <div class="part" id="part3">美食</div> <div class="part" id="part4">家居</div> <div class="part" id="part5">黃金</div> </div> </template>
3.scrollBy
滾動指定的x,y距離。也就是讓他滾動一定距離,不指定坐標(biāo)
優(yōu)點:當(dāng)我們只是做移動,而不是滾到某個指定的元素時
缺點:得自己算出多少距離
這個方法用的少就不舉例了
最后:要注意的點,記住這么幾個操作
1,如果是打開就滾動到指定位置,vue/react項目一定要在你頁面數(shù)據(jù)渲染完成后滾動
2,如果不含有請求,記得在onMounted(vue),或者useEffect(react)中進(jìn)行滾動操作,如果是頁面滾動,可能還要在加一個小延遲(setTimeout)
3,如果頁面的數(shù)據(jù)是請求來的,請確保數(shù)據(jù)渲染完成后進(jìn)行滾動
頁面滾動是會記錄上一次滾動狀態(tài)的,在頁面渲染好后又會滾回去。記錄頁面滾動這個現(xiàn)象一般只限于同步引入的組件,異步的不會(沒有滾動記錄)
總結(jié)
到此這篇關(guān)于前端滾動錨點三個常用方案的文章就介紹到這了,更多相關(guān)前端滾動到指定位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS正則表達(dá)式學(xué)習(xí)之貪婪和非貪婪模式實例總結(jié)
這篇文章主要介紹了JS正則表達(dá)式學(xué)習(xí)之貪婪和非貪婪模式用法,結(jié)合實例形式總結(jié)分析了JS正則表達(dá)式中貪婪模式與非貪婪模式的具體功能、使用方法與相關(guān)注意事項,需要的朋友可以參考下2016-12-12javascript實現(xiàn)移動的模態(tài)框效果
這篇文章主要為大家詳細(xì)介紹了javascript實現(xiàn)移動的模態(tài)框效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09基于bootstrap實現(xiàn)多個下拉框同時搜索功能
這篇文章主要為大家詳細(xì)介紹了基于bootstrap實現(xiàn)多個下拉框同時搜索功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07