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