本程式碼實驗室會說明如何在網路上建構類似 Instagram 限時動態的體驗。我們會逐步建構元件,先從 HTML 開始,接著是 CSS,然後是 JavaScript。
請參閱我的網誌文章「建構 Stories 元件」,瞭解建構這個元件時所做的漸進式強化。
設定
- 按一下「重混即可編輯」,即可編輯專案。
- 開啟
app/index.html。
HTML
我一律會使用語意式 HTML。由於每位好友可以有任意數量的短片,因此我認為為每位好友使用 <section> 元素,並為每則短片使用 <article> 元素,是很有意義的做法。不過,我們還是從頭開始吧。首先,我們需要一個容器來存放精選故事元件。
在 <body> 中新增 <div> 元素:
<div class="stories">
</div>
新增一些 <section> 元素來代表好友:
<div class="stories">
<section class="user"></section>
<section class="user"></section>
<section class="user"></section>
<section class="user"></section>
</div>
新增一些 <article> 元素來代表短片故事:
<div class="stories">
<section class="user">
<article class="story" style="--bg: url(https://picsum.photos/480/840);"></article>
<article class="story" style="--bg: url(https://picsum.photos/480/841);"></article>
</section>
<section class="user">
<article class="story" style="--bg: url(https://picsum.photos/481/840);"></article>
</section>
<section class="user">
<article class="story" style="--bg: url(https://picsum.photos/481/841);"></article>
</section>
<section class="user">
<article class="story" style="--bg: url(https://picsum.photos/482/840);"></article>
<article class="story" style="--bg: url(https://picsum.photos/482/843);"></article>
<article class="story" style="--bg: url(https://picsum.photos/482/844);"></article>
</section>
</div>
- 我們使用圖片服務 (
picsum.com) 協助設計故事原型。 - 每個
<article>上的style屬性是預留位置載入技術的一部分,下一節將詳細說明。
CSS
內容已準備好套用樣式。現在就來為骨架增添血肉,打造出吸引使用者互動的內容。今天我們會以行動裝置優先。
.stories
我們希望 <div class="stories"> 容器是水平捲動容器。做法如下:
- 將容器設為格線
- 將每個子項設為填滿資料列軌
- 將每個子項的寬度設為行動裝置可視區域的寬度
格線會繼續在先前欄的右側放置新的 100vw 寬欄,直到標記中的所有 HTML 元素都放置完畢。
在 app/css/index.css 底部加入下列 CSS:
.stories {
display: grid;
grid: 1fr / auto-flow 100%;
gap: 1ch;
}
現在,我們有超出可視區域的內容,接著要告訴容器如何處理。在 .stories 規則集中加入醒目顯示的程式碼:
.stories {
display: grid;
grid: 1fr / auto-flow 100%;
gap: 1ch;
overflow-x: auto;
scroll-snap-type: x mandatory;
overscroll-behavior: contain;
touch-action: pan-x;
}
我們想要水平捲動,因此將 overflow-x 設為 auto。當使用者捲動時,我們希望元件能輕輕停在下一則報導上,因此會使用 scroll-snap-type: x mandatory。如要進一步瞭解這個 CSS,請參閱網誌文章的「CSS 捲動貼齊點」和「overscroll-behavior」部分。
父項容器和子項都必須同意捲動貼齊,因此我們現在來處理這個問題。將下列程式碼新增至 app/css/index.css 底部:
.user {
scroll-snap-align: start;
scroll-snap-stop: always;
}
您的應用程式目前還無法運作,但下方影片顯示啟用和停用 scroll-snap-type 時會發生的情況。啟用後,每次水平捲動都會貼齊下一個故事。如果停用,瀏覽器會使用預設捲動行為。
這樣就能捲動瀏覽好友,但我們仍有短片故事的問題需要解決。
.user
我們在 .user 區段中建立版面配置,將這些子故事元素整理到適當位置。我們將使用一個方便的堆疊技巧來解決這個問題。
我們基本上會建立 1x1 格線,其中列和欄具有相同的格線別名 [story],且每個故事格線項目都會嘗試並宣告該空間,進而產生堆疊。
將醒目顯示的程式碼新增至 .user 規則集:
.user {
scroll-snap-align: start;
scroll-snap-stop: always;
display: grid;
grid: [story] 1fr / [story] 1fr;
}
在 app/css/index.css 底部新增下列規則集:
.story {
grid-area: story;
}
現在,如果沒有絕對定位、浮動或其他會將元素移出流程的版面配置指令,我們仍會留在流程中。而且幾乎不需要寫程式碼,影片和網誌文章會更詳細地說明這項功能。
.story
現在,我們只需要設定故事項目本身的樣式。
我們在前面提過,每個 <article> 元素上的 style 屬性是預留位置載入技術的一部分:
<article class="story" style="--bg: url(https://picsum.photos/480/840);"></article>
我們將使用 CSS 的 background-image 屬性,指定多張背景圖片。我們可以將它們排序,讓使用者圖片位於最上方,並在載入完成後自動顯示。如要啟用這項功能,請將圖片網址放入自訂屬性 (--bg),並在 CSS 中使用該屬性,與載入預留位置分層。
首先,請更新 .story 規則集,在背景圖片載入完成後,將漸層替換為背景圖片。將醒目顯示的程式碼新增至 .story 規則集:
.story {
grid-area: story;
background-size: cover;
background-image:
var(--bg),
linear-gradient(to top, lch(98 0 0), lch(90 0 0));
}
將 background-size 設為 cover 可確保可視區域中沒有空白空間,因為圖片會填滿可視區域。定義 2 張背景圖片後,我們就能使用一項巧妙的 CSS 網頁技巧,稱為載入墓碑:
- 背景圖片 1 (
var(--bg)) 是我們在 HTML 中內嵌傳遞的網址 - 背景圖片 2 (
linear-gradient(to top, lch(98 0 0), lch(90 0 0))是網址載入時顯示的漸層
圖片下載完成後,CSS 會自動將漸層替換為圖片。
接下來,我們將新增一些 CSS 來移除部分行為,讓瀏覽器能更快移動。將醒目顯示的程式碼新增至 .story 規則集:
.story {
grid-area: story;
background-size: cover;
background-image:
var(--bg),
linear-gradient(to top, lch(98 0 0), lch(90 0 0));
user-select: none;
touch-action: manipulation;
}
user-select: none可防止使用者不小心選取文字touch-action: manipulation會指示瀏覽器將這些互動視為觸控事件,這樣瀏覽器就不必嘗試判斷您是否點選網址
最後,我們加入一些 CSS,讓故事之間的轉場效果更生動。將醒目顯示的程式碼新增至 .story 規則集:
.story {
grid-area: story;
background-size: cover;
background-image:
var(--bg),
linear-gradient(to top, lch(98 0 0), lch(90 0 0));
user-select: none;
touch-action: manipulation;
transition: opacity .3s cubic-bezier(0.4, 0.0, 1, 1);
&.seen {
opacity: 0;
pointer-events: none;
}
}
.seen 類別會新增至需要退出的故事。我從 Material Design 的加/減速指南中取得自訂加/減速函式 (cubic-bezier(0.4, 0.0, 1,1)) (捲動至「加速加/減速」部分)。
如果您觀察敏銳,可能已經注意到 pointer-events: none 宣告,並正在思考其用途。我認為這是目前為止,這項解決方案唯一的缺點。我們需要這個屬性,因為 .seen.story 元素會位於頂端,即使不可見,也會接收輕觸動作。將 pointer-events 設為 none,即可將玻璃故事變成視窗,不再竊取使用者互動。這項取捨還算合理,目前在 CSS 中也不難管理。我們不會同時處理z-index。我還是覺得這個方法不錯。
JavaScript
對使用者來說,精選故事元件的互動方式相當簡單:輕觸右側可向前移動,輕觸左側可向後移動。對使用者來說簡單的事,對開發人員來說往往是艱鉅的工作。不過,我們會處理大部分的工作。
設定
首先,請盡可能計算並儲存資訊。在 app/js/index.js 加入以下程式碼:
const stories = document.querySelector('.stories')
const median = stories.offsetLeft + (stories.clientWidth / 2)
JavaScript 的第一行會擷取並儲存主要 HTML 元素根目錄的參照。下一行會計算元素的中間位置,以便判斷輕觸動作是要向前還是向後。
州
接著,我們建立一個小型物件,其中包含與邏輯相關的狀態。在本例中,我們只對目前的故事感興趣。在 HTML 標記中,我們可以擷取第 1 位好友和他們最新的短片故事來存取。將醒目顯示的程式碼新增至 app/js/index.js:
const stories = document.querySelector('.stories')
const median = stories.offsetLeft + (stories.clientWidth / 2)
const state = {
current_story: stories.firstElementChild.lastElementChild
}
事件監聽器
我們現在有足夠的邏輯,可以開始監聽使用者事件並進行導向。
老鼠
首先,我們來監聽故事容器上的 'click' 事件。在 app/js/index.js 中加入醒目顯示的程式碼:
const stories = document.querySelector('.stories')
const median = stories.offsetLeft + (stories.clientWidth / 2)
const state = {
current_story: stories.firstElementChild.lastElementChild
}
stories.addEventListener('click', e => {
if (e.target.nodeName !== 'ARTICLE')
return
navigateStories(
e.clientX > median
? 'next'
: 'prev')
})
如果點擊事件發生在非 <article> 元素上,則會略過不執行任何動作。
如果是文章,我們會使用 clientX 擷取滑鼠或手指的水平位置。我們尚未實作 navigateStories,但它採用的引數會指定我們需要前往的方向。如果該使用者位置大於中位數,我們就知道需要前往 next,否則前往 prev (上一個)。
鍵盤
現在,我們要監聽鍵盤按壓事件。如果按下向下箭頭,系統會前往 next。如果是向上鍵,則前往 prev。
在 app/js/index.js 中加入醒目顯示的程式碼:
const stories = document.querySelector('.stories')
const median = stories.offsetLeft + (stories.clientWidth / 2)
const state = {
current_story: stories.firstElementChild.lastElementChild
}
stories.addEventListener('click', e => {
if (e.target.nodeName !== 'ARTICLE')
return
navigateStories(
e.clientX > median
? 'next'
: 'prev')
})
document.addEventListener('keydown', ({key}) => {
if (key !== 'ArrowDown' || key !== 'ArrowUp')
navigateStories(
key === 'ArrowDown'
? 'next'
: 'prev')
})
精選故事導覽
現在要來處理限時動態的獨特商業邏輯,以及其著名的使用者體驗。這看起來很複雜,但如果逐行閱讀,就會發現其實不難理解。
首先,我們會儲存一些選取器,協助我們決定是否要捲動至好友,或顯示/隱藏 Story。由於我們是在 HTML 中作業,因此會查詢是否有朋友 (使用者) 或故事 (故事)。
這些變數可協助我們回答以下問題:「假設目前是限時動態 x,『下一則』是指移至同一位好友的另一則限時動態,還是移至不同好友的限時動態?」我使用我們建立的樹狀結構,深入父項和子項。
將下列程式碼新增至 app/js/index.js 底部:
const navigateStories = direction => {
const story = state.current_story
const lastItemInUserStory = story.parentNode.firstElementChild
const firstItemInUserStory = story.parentNode.lastElementChild
const hasNextUserStory = story.parentElement.nextElementSibling
const hasPrevUserStory = story.parentElement.previousElementSibling
}
以下是我們的商業邏輯目標,盡可能接近自然語言:
- 決定如何處理輕觸動作
- 如果有下一則/上一則精選故事:顯示該精選故事
- 如果這是好友的最後一則/第一則短片故事:顯示新好友
- 如果該方向沒有可前往的精選故事:不執行任何動作
- 將新的目前故事暫存到
state
將醒目顯示的程式碼新增至 navigateStories 函式:
const navigateStories = direction => {
const story = state.current_story
const lastItemInUserStory = story.parentNode.firstElementChild
const firstItemInUserStory = story.parentNode.lastElementChild
const hasNextUserStory = story.parentElement.nextElementSibling
const hasPrevUserStory = story.parentElement.previousElementSibling
if (direction === 'next') {
if (lastItemInUserStory === story && !hasNextUserStory)
return
else if (lastItemInUserStory === story && hasNextUserStory) {
state.current_story = story.parentElement.nextElementSibling.lastElementChild
story.parentElement.nextElementSibling.scrollIntoView({
behavior: 'smooth'
})
}
else {
story.classList.add('seen')
state.current_story = story.previousElementSibling
}
}
else if(direction === 'prev') {
if (firstItemInUserStory === story && !hasPrevUserStory)
return
else if (firstItemInUserStory === story && hasPrevUserStory) {
state.current_story = story.parentElement.previousElementSibling.firstElementChild
story.parentElement.previousElementSibling.scrollIntoView({
behavior: 'smooth'
})
}
else {
story.nextElementSibling.classList.remove('seen')
state.current_story = story.nextElementSibling
}
}
}
試試看
- 如要預覽網站,請按下「View App」,然後按下「Fullscreen」
。
結論
以上就是我對這個元件的需求。歡迎以此為基礎,用資料驅動,並打造出專屬的解決方案!