點擊左側選單時,對應的頁面在載入過程中伴隨滑動與淡入過渡,頂部還有一條同步推進的進度條。頁面內容由 Ajax 驅動,整段切換過程流暢不卡頓,是使用者體驗相當加分的一種做法。
.cd-main 承載頁面主體,.cd-side-navigation 是側邊導覽列,#cd-loading-bar 則專門負責進度條動畫。
<nav class="cd-side-navigation"> <ul> <li> <a href="index.html" class="selected" data-menu="index"> <svg><!-- svg content here --></svg> Intro </a> </li> <li> <!-- ... --> </li> <!-- other list items here --> </ul> </nav> <!-- .cd-dashboard --> <main class="cd-main"> <section class="cd-section index visible"> <header> <div class="cd-title"> <h2>Animated Page Transition #2</h2> <span>Some text here</span> </div> <a href="#index-content" class="cd-scroll">Scroll Down</a> </header> <div class="cd-content" id="index-content"> <!-- content here --> </div> <!-- .cd-content --> </section> <!-- .cd-section --> </main> <!-- .cd-main --> <div id="cd-loading-bar" data-scale="1" class="index"></div> <!-- lateral loading bar -->
把 .cd-side-navigation 設為 position: fixed 並給定 100% 高度,左側欄就會固定不動,右側主體內容自行捲動。
.cd-side-navigation { position: fixed; z-index: 3; top: 0; left: 0; height: 100vh; width: 94px; overflow: hidden; } .cd-side-navigation ul { height: 100%; overflow-y: auto; } .cd-side-navigation::before { /* background color of the side navigation */ content: ''; position: absolute; top: 0; left: 0; height: 100%; width: calc(100% - 4px); background-color: #131519; } .cd-side-navigation li { width: calc(100% - 4px); } .cd-side-navigation a { display: block; position: relative; } .cd-side-navigation a::after { /* 4px line to the right of the item - visible on hover */ content: ''; position: absolute; top: 0; right: -4px; height: 100%; width: 4px; background-color: #83b0b9; opacity: 0; } .no-touch .cd-side-navigation a:hover::after { opacity: 1; }
那條 4px 的右側高亮線用偽元素 ::after 搭配 opacity 變化完成,只在使用具備 hover 能力的裝置時顯示,觸控裝置不會出現殘影。
點擊選單後會呼叫 triggerAnimation(),它依序觸發進度條動畫 loadingBarAnimation() 與內容載入 loadNewContent()。
function loadingBarAnimation() { var scaleMax = loadingBar.data('scale'); if( scaleY + 1 < scaleMax) { newScaleValue = scaleY + 1; } // ... loadingBar.velocity({ scaleY: newScaleValue }, 100, loadingBarAnimation); }
進度條靠 scaleY 逐步遞增並自我遞迴呼叫,直到抵達上限為止。
function loadNewContent(newSection) { var section = $('<section class="cd-section overflow-hidden '+newSection+'"></section>').appendTo(mainContent); //load the new content from the proper html file section.load(newSection+'.html .cd-section > *', function(event){ loadingBar.velocity({ scaleY: scaleMax //this is the scaleY value to cover the entire window height (100% loaded) }, 400, function(){ section.addClass('visible'); var url = newSection+'.html'; if(url!=window.location){ //add the new page to the window.history window.history.pushState({path: url},'',url); } // ... }); }); }
新頁面被選取時,會先建立一個 .cd-section 元素插入 DOM,再用 load() 抓取對應 HTML 檔的內容片段;載完後加上 visible 類別觸發過渡,同時以 history.pushState 把網址寫入瀏覽器歷史。
因為每個 section 都寫進了 history,使用者按瀏覽器的返回鍵就能回到上一個畫面,而且同樣會播放過渡動畫。這種「單頁切換 + 真實網址」的組合,兼顧了流暢度與可分享性,比單純用 display 切換來得完整。