為了構(gòu)建一個(gè)閱讀進(jìn)度條,即顯示用戶向下滾動(dòng)時(shí)閱讀文章的進(jìn)度,很難不考慮 JavaScript。但是,事實(shí)證明,您也可以使用純 CSS 構(gòu)建閱讀進(jìn)度條。
從本質(zhì)上講,一個(gè)名為 animation-timeline[1] 的新實(shí)驗(yàn)性 CSS 屬性可以讓你指定用于控制 CSS 動(dòng)畫進(jìn)度的時(shí)間軸。我們將用它來創(chuàng)建閱讀進(jìn)度條。
首先,我們需要定義一個(gè)用作進(jìn)度條的 div 元素。我們將使用一個(gè)固定在視口頂部的容器來包裝這個(gè) div 。這將確保用戶向下滾動(dòng)頁面時(shí)進(jìn)度條始終可見。
<div class="progress-bar-container"> <div class="progress-bar"></div></div><div class="content"> <!-- content goes here --></div>
接下來,我們將定義進(jìn)度條的樣式。我們將設(shè)置 progress-bar-container 固定在視口頂部并調(diào)整其背景顏色,該顏色始終對(duì)用戶可見。我們還將 progress-bar 設(shè)置為 100% 寬度。
.progress-bar-container { position: fixed; top: 0px; width: 100%; background: #6c2fa2; z-index: 999;}
現(xiàn)在,為了使進(jìn)度條動(dòng)畫化,我們將為 progress-bar 使用不同的背景顏色,并將其高度設(shè)置為 7px 。我們還將 animation-name 設(shè)置為 width ,這實(shí)際上將進(jìn)度條的寬度從 0 動(dòng)畫到 100%。
最后,我們將 animation-timeline 設(shè)置為 scroll(y) ,將動(dòng)畫時(shí)間軸綁定到視口的垂直滾動(dòng)位置。這將確保當(dāng)用戶向下滾動(dòng)頁面時(shí)進(jìn)度條具有動(dòng)畫效果。
.progress-bar { height: 7px; background: #e131ff; animation-name: width; /* animation timeline is tied to vertical scroll position */ animation-timeline: scroll(y);}@keyframes width { from { width: 0 } to { width: 100% }}
就是這樣!您可以在下面看到它的實(shí)際效果。
圖片
由于 animation-timeline 屬性仍處于實(shí)驗(yàn)階段,因此并非所有瀏覽器(準(zhǔn)確地說是 Firefox 和 Safari)都支持它。
您可以檢查瀏覽器的兼容性[2]并據(jù)此使用。
圖片
[1]animation-timeline: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timeline
[2]瀏覽器的兼容性: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timeline#browser_compatibility
本文鏈接:http://www.tebozhan.com/showinfo-26-35579-0.html僅用 CSS 實(shí)現(xiàn)網(wǎng)頁閱讀進(jìn)度條
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com