網站導覽

v2.1.0
資料顯示

捲動數字

數值變動時,各位數會像機械計數器的轉輪一樣滾動到新的數字。

本頁內容

數值變動時,各位數會像機械計數器的字輪一樣滾到新的數字。樣式表為每一位繪製一欄垂直排列的數字,並透過一行高的視窗顯示。當頁面變更某一位的 --digit,該欄就會滾到新的數字,數字經過視窗上下緣時會淡入或淡出。這個元件沒有自己的背景或尺寸,因此可以當作統計數據的數值、標題,或句子裡的一個詞。完整數值也會以純文字寫一遍,供螢幕閱讀器讀取。

捲動數字

<div class="card w-full max-w(320)">  <div class="stat">    <p class="stat-label">Visitors today</p>    <div class="stat-row">      <p class="stat-value">        <span class="odometer" id="visitors">          <span class="odometer-value">12,847</span>          <span class="odometer-figures" aria-hidden="true">            <span class="odometer-digit" style="--digit: 1"></span> <span class="odometer-digit" style="--digit: 2"></span>, <span class="odometer-digit" style="--digit: 8"></span> <span class="odometer-digit" style="--digit: 4"></span> <span class="odometer-digit" style="--digit: 7"></span>          </span>        </span>      </p>      <p class="stat-delta stat-delta-up">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M13.6362 7.5189A0.4947 0.4947 0 0 0 13.5 7.5L2.4755 7.5006A0.5 0.5 0 0 0 2.4266 8.4946L2.5 8.5H13.5A0.4947 0.4947 0 0 0 13.6362 8.4811A0.7009 0.7009 0 0 0 13.6362 7.5189Z" fill="currentColor" stroke="none" fill-rule="evenodd" transform="rotate(-90 8 8)" /><path d="M8 4.5L13.2348 7.8313A0.2 0.2 0 0 1 13.2348 8.1687L8 11.5" transform="rotate(-90 8 8)" />        </svg>3.1%      </p>    </div>  </div>  <button class="btn btn-sm self-start" type="button" id="visitors-add">Add visitors</button></div><script>function roll(odometer, text, up) {  odometer.querySelector('.odometer-value').textContent = text  var numerals = text.split('').filter(function (character) { return character >= '0' && character <= '9' })  odometer.querySelectorAll('.odometer-digit').forEach(function (digit, index) {    var at = Number(digit.style.getPropertyValue('--digit')) || 0    var step = ((numerals[index] - at) % 10 + 10) % 10    if (!up && step) step -= 10    digit.style.setProperty('--digit', at + step)  })}var visitors = 12847document.getElementById('visitors-add').addEventListener('click', function () {  visitors += 1 + Math.floor(Math.random() * 240)  roll(document.getElementById('visitors'), visitors.toLocaleString('en-US'), true)})</script>
按下「Add visitors」,有變動的位數就會向上捲動,顯示新的訪客人數。

#標記寫法

同一個數值會寫兩次,分別供輔助技術讀取和畫面呈現:

  • odometer-value 存放純文字數值,並透過裁切將文字隱藏。螢幕閱讀器會將它當作一整段純文字讀出,使用者也能用頁面搜尋找到並複製它。
  • odometer-figures 負責繪製數值,並設有 aria-hidden="true"。每一位各用一個空的 odometer-digit,以 --digit 指定數字。不會滾動的符號,例如逗號、小數點、貨幣符號或單位,則以純文字穿插在各位數之間。

數字採用橫向 flex 版面配置,因此標記中各位數之間的換行和縮排不會在數值裡變成空格。需要留空格時,例如單位前方,請用不換行空格(&nbsp;)。即使頁面是由右至左書寫,各位數仍會依數字的書寫順序由左至右排列。

每一位都用一個不可見的 0 撐出視窗,因此視窗恰好有一個數字寬,並與該行的基線對齊。各個數字採等寬排版,滾動時不會帶動旁邊的內容。

#適用於各種文字樣式

捲動數字會沿用所在位置的字級、字重和文字顏色。視窗大小、數字的垂直間距和淡入淡出範圍也會隨文字樣式調整,因此在標題、統計數據和一般文字行中都能使用相同的捲動機制。

用在標題和句子中

<h3 class="m(0) text-4xl font-semibold fg-text-strong">  <span class="odometer" id="total">    <span class="odometer-value">$1,280.50</span>    <span class="odometer-figures" aria-hidden="true">      $<span class="odometer-digit" style="--digit: 1"></span>, <span class="odometer-digit" style="--digit: 2"></span> <span class="odometer-digit" style="--digit: 8"></span> <span class="odometer-digit" style="--digit: 0"></span>. <span class="odometer-digit" style="--digit: 5"></span> <span class="odometer-digit" style="--digit: 0"></span>    </span>  </span></h3><p class="m(0) text-sm fg-text-muted">  Includes <span class="odometer" id="tax">    <span class="odometer-value">$106.71</span>    <span class="odometer-figures" aria-hidden="true">      $<span class="odometer-digit" style="--digit: 1"></span> <span class="odometer-digit" style="--digit: 0"></span> <span class="odometer-digit" style="--digit: 6"></span>. <span class="odometer-digit" style="--digit: 7"></span> <span class="odometer-digit" style="--digit: 1"></span>    </span>  </span> in tax.</p><button class="btn btn-sm mt-sm" type="button" id="stand" aria-pressed="false">  Add the stand</button><script>function roll(odometer, text, up) {  odometer.querySelector('.odometer-value').textContent = text  var numerals = text.split('').filter(function (character) { return character >= '0' && character <= '9' })  odometer.querySelectorAll('.odometer-digit').forEach(function (digit, index) {    var at = Number(digit.style.getPropertyValue('--digit')) || 0    var step = ((numerals[index] - at) % 10 + 10) % 10    if (!up && step) step -= 10    digit.style.setProperty('--digit', at + step)  })}var stand = document.getElementById('stand')stand.addEventListener('click', function () {  var added = stand.getAttribute('aria-pressed') !== 'true'  stand.setAttribute('aria-pressed', String(added))  stand.textContent = added ? 'Remove the stand' : 'Add the stand'  roll(document.getElementById('total'), added ? '$1,329.50' : '$1,280.50', added)  roll(document.getElementById('tax'), added ? '$110.79' : '$106.71', added)})</script>
按下「Add the stand」,總額和稅額就會向上捲動。再按一次,兩者就會向下滾回原值。

#讓滾動方向跟隨數值增減

每一欄都有 0 到 9,會沿著該欄向上或向下直接滾到指定的數字。若要讓每一位都像機械計數器一樣,沿著數值增減的方向滾動,可以讓 --digit 繼續增加到超過 9,或減到 0 以下。視窗會以 10 為模數決定顯示的數字。從 9 改成 10,會向前滾一格到 0。從 0 改成 -1,則會往回滾一格到 9。

上方預覽的腳本就是這樣做的。它會讀取每一位上次寫入的值,總數增加時向前滾到新數字,減少時向後滾,每一位最多滾九格:

var at = Number(digit.style.getPropertyValue('--digit')) || 0var step = ((numeral - at) % 10 + 10) % 10if (!up && step) step -= 10digit.style.setProperty('--digit', at + step)

沒有腳本時,元件只會顯示數值。如果頁面只呈現一次數值,使用 0 到 9 就足夠了。

#動畫時序

每一位的動畫時間由 --odometer-duration 設定,長度是主題基準時間的兩倍,並沿用主題統一的緩動曲線。動畫起步快、收尾平緩,讓新數字很快就能辨認。每一位都比前一位晚 --odometer-stagger 開始滾動,因此能從左到右看出變化。淡出效果避開了中央數字的完整高度,相鄰數字也停在視窗外,因此靜止時只會看到當前數值。

#無障礙

  • 螢幕閱讀器只會讀取 odometer-value。請讓它與畫面上的數值一致,包含分隔符號和單位,並與各位數同步更新。
  • odometer-figures 必須加上 aria-hidden="true"。各欄的數字是由 CSS 產生的內容,替代文字為空,但位數之間的符號是實際文字,若未隱藏就會被重複讀出。
  • 捲動數字本身不是即時區域。如果使用者需要聽到新數值,例如做出選擇後的總額,請在 odometer 根元素加上 aria-live="polite"。根元素中唯一可供讀取的文字是經裁切隱藏的數值,因此新數值只會播報一次。若數值每隔幾秒就會自行變動,請勿加上這個屬性。
  • 啟用減少動態效果時,數字會在原位直接切換。強制色彩模式下,數字會使用系統文字顏色。

#平台支援

滾動動畫會對已註冊的自訂屬性(@property)套用緩動,視窗則透過 mod() 以 10 為模數取得顯示值。瀏覽器若不支援 @property,數字會在原位切換。若不支援 mod(),請將 --digit 維持在 0 到 9。各位數之間的延遲使用 sibling-index(),在支援的瀏覽器(Chromium)中生效,其他瀏覽器則會讓各位數一起滾動。

#類別

類別說明
odometer數字沿用所在位置的文字樣式,並使用等寬數字。元件本身沒有背景,也未指定尺寸。
odometer-value數字的純文字版本會裁切隱藏,供輔助技術讀取、頁面內搜尋與複製使用。
odometer-figures數字的視覺呈現會對輔助技術隱藏。內容包括數字字元,以及穿插其中、維持靜止的純文字,例如逗號、小數點、貨幣符號或單位。
odometer-digit每個數字使用一個空元素,形成一行高的視窗,顯示直向數字列中由 --digit 指定的數字。值改變時,數字列會滾動。

#自訂屬性

屬性預設值說明
--digit顯示 0 到 9 的單一數字。超過 9 或低於 0 時,取模 10 的結果,因此從 9 數到 10 時只會向前滾動一格,顯示 0。未設定時,樣式表會採用 0。設定於 odometer-digit
--odometer-durationcalc(var(--duration-base) * 2)單一數字滾動切換到新值所需的時間
--odometer-stagger24ms每一位數字比前一位晚多久開始動作

#原始程式碼

@master/ui/components/odometer.css
/* * Odometer: a number whose digits roll to their new value, like the wheels of a mechanical counter. * It has no surface and no size of its own: it takes the type of the place it stands in, a heading, a stat's * figure or a line of text, and sets tabular figures so every digit is as wide as the next and nothing beside * the number moves while it rolls. * The number is written twice, once for each reader. odometer-value holds it as text, clipped out of sight, so * assistive technology reads one plain string, and find in page and a copy take the number; odometer-figures, * aria-hidden, draws it. In the figures each odometer-digit is a window one line tall onto a column of * numerals drawn by the stylesheet, standing at --digit. A change of --digit eases the column to the new * numeral, and a mask fades it out over and under the line, so numerals roll in and out of sight instead of * being cut. Anything else in the figures, a comma, a point, a currency or a unit, is plain text and stands still. * A wheel goes round: --digit may count on past 9 or below 0, and the window shows it modulo ten, so 9 to 10 * rolls on to 0 and 0 to -1 rolls back to 9, one step each, as a counter does. * Platform: the roll eases a registered number (@property) and the wheel reads it with mod(). Without * @property the numeral changes in place; without mod(), write --digit from 0 to 9. Where sibling-index() is * supported, each digit sets off a little after the one before it, so a change reads left to right; elsewhere * they roll together. Under reduced motion the numerals change in place. */@property --odometer-at {  syntax: '<number>';  inherits: true;  initial-value: 0;}@layer components.ui {  .odometer {    --odometer-duration: calc(var(--duration-base) * 2);    --odometer-stagger: 24ms;    position: relative;    font-variant-numeric: tabular-nums;    white-space: nowrap;  }  /* The number as text, for assistive technology, find in page and copying; clipped out of sight. */  .odometer-value {    position: absolute;    width: 1px;    height: 1px;    margin: -1px;    padding: 0;    overflow: hidden;    clip-path: inset(50%);    white-space: nowrap;  }  /*   * The drawing. A flex row, so the whitespace between digits in the markup never becomes a space in the   * number, and left to right in any direction of text, as numbers are written.   */  .odometer-figures {    display: inline-flex;    align-items: baseline;    direction: ltr;    unicode-bidi: isolate;    user-select: none;    -webkit-user-select: none;  }  /*   * One digit. A hidden zero gives the window a numeral's width and the line's baseline. The window is the   * line itself, reaching a hair over and under it, and gives that hair back with a negative margin, so the   * line keeps its height and a rolling numeral never crosses into the line above or below. The mask is clear   * across a numeral's own height and fades out by the window's edge, as the wheel turns away. The window   * clips the column too: a mask hides the other numerals but would leave them making the page scroll.   */  .odometer-digit {    --odometer-reach: .08em;    --odometer-at: var(--digit, 0);    position: relative;    display: block;    padding-block: var(--odometer-reach);    margin-block: calc(var(--odometer-reach) * -1);    overflow: clip;    mask-image: linear-gradient(transparent, black calc(50% - .38em), black calc(50% + .38em), transparent);    transition: --odometer-at var(--odometer-duration) var(--easing-glide);    @supports (width: calc(sibling-index() * 1px)) {      transition-delay: calc((sibling-index() - 1) * var(--odometer-stagger));    }    /*     * The column: 0 to 9 and 0 again, so a roll past 9 ends on a 0 that looks like the first. Numerals are     * spaced .4em further apart than lines of text, so the next one waits outside the box, and each stands in     * the middle of its line, as the line's own numeral does.     */    &::before {      content: '0\A 1\A 2\A 3\A 4\A 5\A 6\A 7\A 8\A 9\A 0';      content: '0\A 1\A 2\A 3\A 4\A 5\A 6\A 7\A 8\A 9\A 0' / '';      position: absolute;      inset: calc(var(--odometer-reach) - .2em) 0 auto;      line-height: calc(1lh + .4em);      text-align: center;      white-space: pre;      translate: 0 calc(var(--odometer-at) * -1lh);      @supports (width: calc(mod(3px, 2px))) {        translate: 0 calc(mod(var(--odometer-at), 10) * -1lh);      }    }    &::after {      content: '0';      content: '0' / '';      visibility: hidden;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }}