頁面平滑滾動小技巧
阿新 • • 發佈:2020-12-12
背景
今天寫需求的時候發現一個小的優化點:使用者選擇了一些資料之後, 對應列表中的資料需要高亮, 有時候列表很長, 為了提升使用者體驗,需要加個滾動, 自動滾動到目標位置。簡單的處理了一下, 問題順利解決, 就把這個小技巧分享一下給大家。
正文
有幾種不同的方式來解決這個小問題。
1.scrollTop
第一想到的還是scrollTop, 獲取元素的位置, 然後直接設定:
// 設定滾動的距離
element.scrollTop = value;
不過這樣子有點生硬, 可以加個緩動:
var scrollSmoothTo = function (position) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
return setTimeout(callback, 17);
};
}
// 當前滾動高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 滾動step方法
var step = function () {
// 距離目標滾動距離
var distance = position - scrollTop;
// 目標滾動位置
scrollTop = scrollTop + distance / 5;
if (Math.abs(distance) < 1) {
window.scrollTo(0, position);
} else {
window.scrollTo(0, scrollTop);
requestAnimationFrame(step);
}
};
step();
};
// 平滑滾動到頂部,可以直接:
scrollSmoothTo(0)
jQuery 中重的animate 方法也可以實現類似的效果:
$('xxx').animate({
scrollTop: 0
});
2. scroll-behavior
把 scroll-behavior:smooth; 寫在滾動容器元素上,也可以讓容器(非滑鼠手勢觸發)的滾動變得平滑。
.list {
scroll-behavior: smooth;
}
在PC上, 網頁預設滾動是在<html>標籤上的,移動端大多數在<body> 標籤上, 那麼這行定義到全域性的css中就是:
html, body {
scroll-behavior:smooth;
}
美滋滋。
資源搜尋網站大全 https://www.renrenfan.com.cn 廣州VI設計公司https://www.houdianzi.com
3. scrollIntoView
Element.scrollIntoView()方法, 讓當前的元素滾動到瀏覽器視窗的可視區域內。
語法:
var element = document.getElementById("box");
element.scrollIntoView(); // 等同於element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型引數
element.scrollIntoView(scrollIntoViewOptions); // Object型引數
scrollIntoView 方法接受兩種形式的值:
- 布林值
-
如果為true,元素的頂端將和其所在滾動區的可視區域的頂端對齊。
- 相應的scrollIntoViewOptions: {block: "start", inline: "nearest"}。這是這個引數的預設值。
-
如果為false,元素的底端將和其所在滾動區的可視區域的底端對齊。
- 相應的scrollIntoViewOptions: { block: "end", inline: "nearest" }。
- Options 物件
{
behavior: "auto" | "instant" | "smooth", 預設為 "auto"。
block: "start" | "end", 預設為 "start"。
inline: "start"| "center"| "end", | "nearest"。預設為 "nearest"。
}
- behavior表示滾動方式。auto表示使用當前元素的scroll-behavior樣式。instant和smooth表示直接滾到底和使用平滑滾動。
- block表示塊級元素排列方向要滾動到的位置。對於預設的writing-mode: horizontal-tb來說,就是豎直方向。start表示將視口的頂部和元素頂部對齊;center表示將視口的中間和元素的中間對齊;end表示將視口的底部和元素底部對齊;nearest表示就近對齊。
- inline表示行內元素排列方向要滾動到的位置。對於預設的writing-mode: horizontal-tb來說,就是水平方向。其值與block類似。
scrollIntoView瀏覽器相容性
最後我用的是scrollIntoView, 問題完美解決。