背景
今天寫需求的時候發(fā)現(xiàn)一個小的優(yōu)化點:用戶選擇了一些數(shù)據(jù)之后, 對應(yīng)列表中的數(shù)據(jù)需要高亮, 有時候列表很長, 為了提升用戶體驗,需要加個滾動, 自動滾動到目標(biāo)位置。
簡單的處理了一下, 問題順利解決, 就把這個小技巧分享一下給大家。
正文
有幾種不同的方式來解決這個小問題。
1.scrollTop
第一想到的還是scrollTop, 獲取元素的位置, 然后直接設(shè)置:
// 設(shè)置滾動的距離
element.scrollTop = value;
不過這樣子有點生硬, 可以加個緩動:
var scrollSmoothTo = function (position) {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
return setTimeout(callback, 17);
};
}
// 當(dāng)前滾動高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 滾動step方法
var step = function () {
// 距離目標(biāo)滾動距離
var distance = position - scrollTop;
// 目標(biāo)滾動位置
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 方法也可以實現(xiàn)類似的效果:
$('xxx').animate({
scrollTop: 0
});
2. scroll-behavior
把 scroll-behavior:smooth; 寫在滾動容器元素上,也可以讓容器(非鼠標(biāo)手勢觸發(fā))的滾動變得平滑。
.list {
scroll-behavior: smooth;
}
在PC上, 網(wǎng)頁默認(rèn)滾動是在<html>標(biāo)簽上的,移動端大多數(shù)在<body> 標(biāo)簽上, 那么這行定義到全局的css中就是:
html, body {
scroll-behavior:smooth;
}
美滋滋。
3. scrollIntoView
Element.scrollIntoView()
方法, 讓當(dāng)前的元素滾動到瀏覽器窗口的可視區(qū)域
內(nèi)。
語法:
var element = document.getElementById("box");
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型參數(shù)
element.scrollIntoView(scrollIntoViewOptions); // Object型參數(shù)
scrollIntoView 方法接受兩種形式的值:
布爾值
如果為true
,元素的頂端將和其所在滾動區(qū)的可視區(qū)域的頂端對齊。
- 相應(yīng)的
scrollIntoViewOptions: {block: "start", inline: "nearest"}
。這是這個參數(shù)的默認(rèn)值。
如果為false,
元素的底端將和其所在滾動區(qū)的可視區(qū)域的底端對齊。
- 相應(yīng)的
scrollIntoViewOptions: { block: "end", inline: "nearest" }
。Options 對象
{
behavior: "auto" | "instant" | "smooth", 默認(rèn)為 "auto"。
block: "start" | "end", 默認(rèn)為 "start"。
inline: "start"| "center"| "end", | "nearest"。默認(rèn)為 "nearest"。
}
behavior
表示滾動方式。auto
表示使用當(dāng)前元素的scroll-behavior
樣式。instant
和smooth
表示直接滾到底
和使用平滑滾動
。
block
表示塊級元素排列方向要滾動到的位置。對于默認(rèn)的writing-mode: horizontal-tb
來說,就是豎直方向。start
表示將視口的頂部和元素頂部對齊;center
表示將視口的中間和元素的中間對齊;end
表示將視口的底部和元素底部對齊;nearest
表示就近對齊。
inline
表示行內(nèi)元素排列方向要滾動到的位置。對于默認(rèn)的writing-mode: horizontal-tb
來說,就是水平方向。其值與block
類似。
scrollIntoView 瀏覽器兼容性

最后我用的是 scrollIntoView
, 問題完美解決。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。