新聞中心
這篇文章主要介紹web開發(fā)中實(shí)現(xiàn)一個(gè)頁面平滑滾動(dòng)小技巧有哪些,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
背景
寫需求的時(shí)候發(fā)現(xiàn)一個(gè)小的優(yōu)化點(diǎn):用戶選擇了一些數(shù)據(jù)之后, 對應(yīng)列表中的數(shù)據(jù)需要高亮, 有時(shí)候列表很長, 為了提升用戶體驗(yàn),需要加個(gè)滾動(dòng), 自動(dòng)滾動(dòng)到目標(biāo)位置。
正文
有幾種不同的方式來解決這個(gè)小問題。
1.scrollTop
第一想到的還是scrollTop, 獲取元素的位置, 然后直接設(shè)置:
// 設(shè)置滾動(dòng)的距離 element.scrollTop = value;
不過這樣子有點(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; 寫在滾動(dòng)容器元素上,也可以讓容器(非鼠標(biāo)手勢觸發(fā))的滾動(dòng)變得平滑。
.list { scroll-behavior: smooth; }
在PC上, 網(wǎng)頁默認(rèn)滾動(dòng)是在標(biāo)簽上的,移動(dòng)端大多數(shù)在
標(biāo)簽上, 那么這行定義到全局的css中就是:html, body { scroll-behavior:smooth; }
美滋滋。
3. scrollIntoView
Element.scrollIntoView()
方法, 讓當(dāng)前的元素滾動(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
,元素的頂端將和其所在滾動(dòng)區(qū)的可視區(qū)域的頂端對齊。
相應(yīng)的
scrollIntoViewOptions: {block: "start", inline: "nearest"}
。這是這個(gè)參數(shù)的默認(rèn)值。
如果為false,
元素的底端將和其所在滾動(dòng)區(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
表示滾動(dòng)方式。auto
表示使用當(dāng)前元素的scroll-behavior
樣式。instant
和smooth
表示直接滾到底
和使用平滑滾動(dòng)
。block
表示塊級元素排列方向要滾動(dòng)到的位置。對于默認(rèn)的writing-mode: horizontal-tb
來說,就是豎直方向。start
表示將視口的頂部和元素頂部對齊;center
表示將視口的中間和元素的中間對齊;end
表示將視口的底部和元素底部對齊;nearest
表示就近對齊。inline
表示行內(nèi)元素排列方向要滾動(dòng)到的位置。對于默認(rèn)的writing-mode: horizontal-tb
來說,就是水平方向。其值與block
類似。
scrollIntoView 瀏覽器兼容性
最后我用的是scrollIntoView
, 問題完美解決。
以上是“web開發(fā)中實(shí)現(xiàn)一個(gè)頁面平滑滾動(dòng)小技巧有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章標(biāo)題:web開發(fā)中實(shí)現(xiàn)一個(gè)頁面平滑滾動(dòng)小技巧有哪些-創(chuàng)新互聯(lián)
URL標(biāo)題:http://www.dlmjj.cn/article/dejgej.html