scrollIntoView
Element.scrollIntoView() 方法讓當前的元素滾動到瀏覽器窗口的可視區域內。
scrollIntoView 可以帶有 alignToTop 參數和 scrollIntoViewOptions。
scrollIntoView(alignToTop):這裏 alignToTop 是一個布爾類型值,如果爲true
那麼元素會在可視區域頂端顯示,對應 scrollIntoViewOptions 對象參數的block:"start"
值;如果值爲false
那麼元素會在可視區域的地步顯示,與底部對齊,對應 scrollIntoViewOptions 參數值的block:"end"
值。
scrollIntoView(scrollIntoViewOptions):這裏的 scrollIntoViewOptions 是一個對象字面量形式的對象,可設置的屬性:
{
behavior: "auto"(默認值) | "instant" | "smooth", // 動畫過渡效果
block: "start"(默認值) |"center"| "end" | "nearest", // 垂直方向對齊
inline: "start"| "center"| "end" | "nearest"(默認值) // 水平方向對齊
}
栗子:
element.scrollIntoView({
behavior: "instant",
block: "end",
inline: "nearest"
});
使用場景:錨點
<div onclick="clickFun">title</div>
<div id="name"></div>
點擊 title, id 爲 name 的元素(連帶它直系父級)就會滾動到可視區域的中間。
function clickFun() {
document.getElementById("name").scrollIntoView({ block: "center" });
}
window.scrollXX
window.scrollXX 可以滾動窗口至文檔中的特定位置。
- window.scroll(x,y):相對於左上角橫縱座標。
- window.scrollTo(x,y):相對於瀏覽器窗體左上角橫縱座標;window.scrollTo(options):options 是一個包含三個屬性的對象
{top:'',left:'',behavior:''}
behavior 類型 String,表示滾動行爲,支持參數 smooth(平滑滾動),instant(瞬間滾動),默認值 auto,實測效果等同於 instant。
window.scrollTo({
top: 1000,
behavior: "smooth"
});
- window.scrollBy:相對於當前所在區域滾動條的位置滾動,滾動行爲參數和 scrollTo 的一致。
scrollBehavior
只在支持 history.pushState 的瀏覽器中可用
pushState 和 replaceState 是 HTML5 提供的新接口,可以改變網址不刷新界面。pushState 使用栗子:
window.history.pushState(state, pageTitle, 'address')
pushState 可以記錄歷史,也就是說使用 pushState 當點擊瀏覽器回退界面按鈕時能夠返回到上一頁。replaceState 和 pushState 使用方法一樣,但它不會記錄地址歷史,點擊回退會返回到上上頁。
使用 Vue 創建項目,如果在路由切換的時候有需要記住界面滾動位置的情況,可以使用scrollBehavior
。
scrollBehavior 方法接收 to 和 from 路由對象。第三個參數 savedPosition 當且僅當 popstate 導航 (通過瀏覽器的 前進/後退 按鈕觸發) 時纔可用。
創建一個 router 實例
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滾動到哪個的位置
}
})
頁面滾動到頂部
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
按 後退/前進 時觸發
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
}
滾動到錨點
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash
}
}
}