網站導覽

v2.1.0
媒體

圖片比較

用滑柄移動兩張圖片的分隔線,比較同一事物的不同樣貌。

本頁內容

圖片比較將同一事物的兩張圖片疊在一起,讓讀者移動分隔線,比較編輯前後、淺色與深色,或草稿與修訂版。滑柄是原生的 <input type="range">,因此具備滑桿的鍵盤操作、數值與可存取名稱。細細的分隔線上有一個珍珠般的滑塊,上層圖片沿著這條線裁切。

圖片比較

<figure class="compare max-w(520) mx-auto">  <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">  <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">  <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture"></figure><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLElement>(null)  useEffect(() => attach(root.current!), [])  return (    <figure ref={root} className="compare max-w(520) mx-auto">      <img className="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style={{ aspectRatio: '16 / 10', filter: 'grayscale(1) contrast(.75)' }} />      <img className="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading" />      <input type="range" className="compare-range" min="0" max="100" defaultValue="50" aria-label="Show more of the graded picture" />    </figure>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><figure class="compare max-w(520) mx-auto" {@attach attach}>  <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">  <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">  <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture"></figure>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <figure ref="root" class="compare max-w(520) mx-auto">    <img class="compare-before" src="/demo/moonstone.svg" alt="The landscape before grading: grey and flat" style="aspect-ratio: 16 / 10; filter: grayscale(1) contrast(.75)">    <img class="compare-after" src="/demo/moonstone.svg" alt="The landscape after grading">    <input type="range" class="compare-range" min="0" max="100" value="50" aria-label="Show more of the graded picture">  </figure></template>
拖曳滑柄,或將焦點移到滑柄上,再按方向鍵。

#用滑柄調整圖片的顯示範圍

瀏覽器支援捲動驅動動畫時,外框會讀取以輸入元件內的滑塊為主體的檢視時間軸。--compare-position 無須腳本就會跟隨滑塊移動,圖片裁切範圍與分隔線也會隨這個屬性更新。

在其他瀏覽器中,compare 行為會在掛載時及每次滑柄移動時,將輸入值換算為它在數值範圍內的百分比,寫入根元素的 --compare-position。請在所有瀏覽器中掛載這個行為。若樣式表已驅動這個屬性,腳本就不會影響畫面。

app.js
import { compare } from '@master/ui/behaviors/compare.js'const detach = compare(document.querySelector('.compare'))

這個行為接受帶有 compare 類別的根元素,沒有選項,也不會自行派發事件。輸入元件和其他範圍輸入元件一樣會派發 input 和 change,而 value 就是分隔線的位置。如果樣式表的時間軸和這個行為都未啟用,兩張圖片會固定以 --compare-position 指定的位置為界,預設在正中央。

輸入元件比外框多出一個滑柄的寬度,因此滑柄的中心可以從外框的一側移到另一側,讓分隔線抵達兩端。

#圖片

compare-before 位於下層,顯示從起始側到分隔線的部分。compare-after 位於上層,顯示從分隔線到結束側的部分。兩張圖片都會填滿外框,超出部分會被裁切。請為其中一張設定寬度和高度,或設定 aspect-ratio,並使用取景一致的兩張圖片。

外框沿用介面的圓角樣式,並帶有所有圖文呈現元件共有的內側描邊。放進卡片時,可用 --compare-radius 調整圓角。

放在卡片中

<div class="card w(280)">  <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">    <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">    <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">    <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">  </figure>  <div class="card-header">    <h3 class="card-title">Warm</h3>    <p class="card-description">Drag to compare with the original.</p>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="card w(280)">      <figure className="compare card-media" style={{ '--compare-radius': 'calc(var(--radius-surface) - 4px)' } as React.CSSProperties}>        <img className="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style={{ aspectRatio: '4 / 3', filter: 'saturate(.2) brightness(.92)' }} />        <img className="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset" />        <input type="range" className="compare-range" min="0" max="100" defaultValue="40" aria-label="Show more of the Warm preset" />      </figure>      <div className="card-header">        <h3 className="card-title">Warm</h3>        <p className="card-description">Drag to compare with the original.</p>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="card w(280)" {@attach attach}>  <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">    <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">    <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">    <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">  </figure>  <div class="card-header">    <h3 class="card-title">Warm</h3>    <p class="card-description">Drag to compare with the original.</p>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="card w(280)">    <figure class="compare card-media" style="--compare-radius: calc(var(--radius-surface) - 4px)">      <img class="compare-before" src="/demo/portrait-1.svg" alt="The portrait as uploaded" style="aspect-ratio: 4 / 3; filter: saturate(.2) brightness(.92)">      <img class="compare-after" src="/demo/portrait-1.svg" alt="The portrait with the Warm preset">      <input type="range" class="compare-range" min="0" max="100" value="40" aria-label="Show more of the Warm preset">    </figure>    <div class="card-header">      <h3 class="card-title">Warm</h3>      <p class="card-description">Drag to compare with the original.</p>    </div>  </div></template>

#鍵盤操作

鍵盤操作完全由原生範圍輸入元件提供。

按鍵動作
ArrowLeft, ArrowRight, ArrowUp, ArrowDown將分隔線移動一格,行為與原生範圍輸入控制項相同
Home, End完整顯示一張圖片

#無障礙

  • 依滑動後的效果為輸入元件命名,例如「顯示更多調色後的圖片」。
  • 為每張圖片提供 alt,說明它是哪一張,以及與另一張有何差異。無法並排觀看兩張圖片的讀者需要透過文字得知差異。
  • 滑柄在 Tab 順序中占一個焦點位置。方向鍵每次移動分隔線一格,Home 和 End 各會完整顯示其中一張圖片。
  • 無論使用哪種指標裝置,可見滑塊的尺寸都是 32px。在觸控螢幕上,滑柄的觸控區域高 44px。手指從外框上垂直滑過時,仍可捲動頁面。

#React、Svelte 和 Vue

compare 元件會掛載行為,並接收與回傳滑柄位置。兩張圖片仍由頁面自己的標記定義。執行 npx master-ui add compare 將元件複製到專案中。React、Svelte 和 Vue 說明元件的建置與使用方式。

ui/compare.tsx
'use client'import { useState, type ComponentProps } from 'react'import { compare } from '@master/ui/behaviors/compare.js'import { useBehavior } from './use-behavior'export interface CompareProps extends Omit<ComponentProps<'figure'>, 'defaultValue' | 'ref'> {  /** How much of the second picture shows, from 0 to 100. */  value?: number  defaultValue?: number  onValueChange?: (value: number) => void  /** The name of the handle: what moving it shows. */  label: string}/** Two pictures and the line between them. The children are the two images, `compare-before` and `compare-after`. */export function Compare({ value, defaultValue = 50, onValueChange, label, className, children, ...root }: CompareProps) {  const ref = useBehavior(compare, undefined, { value, defaultValue, onValueChange })  const [first] = useState(value ?? defaultValue)  return (    <figure className={className ? `compare ${className}` : 'compare'} ref={ref} {...root}>      {children}      <input type="range" className="compare-range" min={0} max={100} defaultValue={first} aria-label={label} />    </figure>  )}
ui/Compare.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  export interface CompareProps extends HTMLAttributes<HTMLElement> {    /** How much of the second picture shows, from 0 to 100. Bind it, or leave it out: it starts at 50. */    value?: number    onValueChange?: (value: number) => void    /** The name of the handle: what moving it shows. */    label: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { compare } from '@master/ui/behaviors/compare.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, label, class: className, children, ...root }: CompareProps = $props()  const first = untrack(() => value) ?? 50  const attach = behavior(compare, undefined, {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  Two pictures and the line between them. The children are the two images, `compare-before` and `compare-after`.--><figure class={['compare', className]} {@attach attach} {...root}>  {@render children?.()}  <input type="range" class="compare-range" min="0" max="100" value={first} aria-label={label} /></figure>
ui/Compare.vue
<script setup lang="ts">import { useTemplateRef } from 'vue'import { compare } from '@master/ui/behaviors/compare.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })defineProps<{  /** The name of the handle: what moving it shows. */  label: string}>()/** How much of the second picture shows, from 0 to 100: `v-model`. */const model = defineModel<number>({ default: 50 })/* Two pictures and the line between them. The default slot is the two images, `compare-before` and `compare-after`. */const first = model.valueconst root = useTemplateRef<HTMLElement>('root')useBehavior(root, compare, undefined, model)</script><template>  <figure class="compare" ref="root" v-bind="$attrs">    <slot />    <input type="range" class="compare-range" min="0" max="100" :value.attr="first" :aria-label="label">  </figure></template>

#類別

類別說明
compare外框將兩張圖片疊放、繪製分隔線,並沿用介面面板的圓角
compare-before下層圖片只顯示從起點到分隔線的範圍。
compare-after上層圖片沿分隔線裁切,只顯示從分隔線到末端的範圍。
compare-range拖曳把手採用橫跨外框的範圍輸入控制項,隱藏軌道,並以握把呈現滑塊。請依移動把手的作用為控制項命名

#自訂屬性

屬性預設值說明
--compare-position分隔線的位置,以距起點的百分比表示。註冊時的初始值為 50%,樣式表或腳本會依把手的位置設定此值
--compare-radiusvar(--radius-surface)外框圓角。嵌入卡片時可調小。
--compare-grip2rem握把的大小;低精確度指標下,握把周圍的滑柄至少高 2.75rem

#原始碼

@master/ui/components/compare.css
/* * Compare: two pictures of the same thing, one over the other, and a handle that draws the line between them. * The handle is a native range input: it has the keys, the value and the name of a slider. Its thumb is a * pearl grip on a fine line; the picture on top is clipped at the line. * Where scroll-driven animations exist the thumb's own place in the input sets --compare-position, so the * picture follows the handle with no script. Elsewhere a script copies the input's value into the same * property, and without either the pictures stay parted where --compare-position puts them. * The input is one grip wider than the frame, so the middle of the grip runs from one edge to the other. */@property --compare-position {  syntax: '<percentage>';  inherits: true;  initial-value: 50%;}@layer components.ui {  .compare {    --compare-radius: var(--radius-surface);    --compare-grip: 2rem;    position: relative;    display: grid;    min-width: 0;    margin: 0;    border-radius: calc(var(--compare-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: clip;    background: var(--color-surface-chip);    user-select: none;    -webkit-user-select: none;    isolation: isolate;    /* The line between the two pictures: pearl, with a faint dark edge so it holds on a pale picture. */    &::before {      content: '';      position: absolute;      inset-block: 0;      inset-inline-start: var(--compare-position);      z-index: 1;      width: 1.5px;      translate: -50% 0;      background: var(--color-on-image);      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 0 6px var(--color-on-image-shade);      pointer-events: none;    }    &:dir(rtl)::before {      translate: 50% 0;    }    /* The inward edge every picture gets, drawn over both of them. */    &::after {      content: '';      position: absolute;      inset: 0;      z-index: 2;      border-radius: inherit;      corner-shape: inherit;      box-shadow: inset 0 0 0 1px var(--color-line-image);      pointer-events: none;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;      &::before {        background: CanvasText;      }    }  }  /* The two pictures share one cell and one size. */  .compare-before, .compare-after {    display: block;    grid-area: 1 / 1;    width: 100%;    height: 100%;    max-width: none;    margin: 0;    object-fit: cover;    pointer-events: none;  }  /* The one on top shows from the line to the end. */  .compare-after {    clip-path: inset(0 0 0 var(--compare-position));    &:dir(rtl) {      clip-path: inset(0 var(--compare-position) 0 0);    }  }  /* The handle: a range input across the middle of the frame, with no track and a grip for a thumb. */  .compare-range {    position: absolute;    inset-block-start: 50%;    inset-inline: calc(var(--compare-grip) / -2);    z-index: 3;    width: calc(100% + var(--compare-grip));    /*     * 4px taller than the grip above and below, where its track stays centered: the focus ring stands 4px outside     * the grip, and the input clips what it holds where it is the grip's view timeline.     */    height: calc(var(--compare-grip) + .5rem);    margin: 0;    padding: 0;    border: 0;    translate: 0 -50%;    background: transparent;    appearance: none;    cursor: ew-resize;    touch-action: pan-y;    -webkit-tap-highlight-color: transparent;    &:focus-visible {      outline: none;    }    &::-webkit-slider-runnable-track {      height: var(--compare-grip);      background: transparent;    }    /* The grip: the pearl thumb of a slider, larger, with a pair of chevrons to say which way it goes. */    &::-webkit-slider-thumb {      width: var(--compare-grip);      height: var(--compare-grip);      border: 0;      border-radius: 999px;      background:        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='none' stroke='%2334353a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m13 12-4 4 4 4M19 12l4 4-4 4'/%3E%3C/svg%3E") center / contain no-repeat,        linear-gradient(180deg, var(--color-thumb-high), var(--color-thumb-low));      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade), 0 8px 16px -8px var(--color-on-image-shade);      appearance: none;      transition: scale var(--duration-quick) var(--easing-glide);    }    &::-moz-range-track {      height: var(--compare-grip);      background: transparent;    }    &::-moz-range-thumb {      width: var(--compare-grip);      height: var(--compare-grip);      border: 0;      border-radius: 999px;      background:        url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='none' stroke='%2334353a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m13 12-4 4 4 4M19 12l4 4-4 4'/%3E%3C/svg%3E") center / contain no-repeat,        linear-gradient(180deg, var(--color-thumb-high), var(--color-thumb-low));      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade), 0 8px 16px -8px var(--color-on-image-shade);      transition: scale var(--duration-quick) var(--easing-glide);    }    /* Held, the grip swells a little; a disabled handle is not held and does not answer. */    &:active:not(:disabled)::-webkit-slider-thumb {      scale: 1.06;    }    &:active:not(:disabled)::-moz-range-thumb {      scale: 1.06;    }    &:disabled {      cursor: default;    }    &:focus-visible::-webkit-slider-thumb {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: 0 0 0 2px var(--color-focus), 0 0 0 .5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade);    }    &:focus-visible::-moz-range-thumb {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: 0 0 0 2px var(--color-focus), 0 0 0 .5px var(--color-on-image-shade), 0 3px 6px -2px var(--color-on-image-shade);    }    /* On touch the input reaches 44px tall around the grip, which keeps its size; a finger anywhere on it moves the line. */    @media (pointer: coarse) {      height: max(var(--compare-grip) + .5rem, 2.75rem);    }    @media (prefers-reduced-motion: reduce) {      &:active:not(:disabled)::-webkit-slider-thumb {        scale: none;      }      &:active:not(:disabled)::-moz-range-thumb {        scale: none;      }    }    @media (forced-colors: active) {      &::-webkit-slider-thumb {        forced-color-adjust: none;        background: ButtonText;        box-shadow: none;      }      /* A selector list with an unknown vendor pseudo-element is dropped whole, so each engine has its own rule. */      &::-moz-range-thumb {        forced-color-adjust: none;        background: ButtonText;        box-shadow: none;      }      &:focus-visible::-webkit-slider-thumb {        outline-color: Highlight;      }      &:focus-visible::-moz-range-thumb {        outline-color: Highlight;      }    }  }  /* The handle moves the picture: the grip is a view timeline in its input and the frame reads it. */  @supports (view-timeline: --compare-grip inline) and (timeline-scope: --compare-grip) {    .compare {      timeline-scope: --compare-grip;      animation-name: compare-position;      animation-timing-function: linear;      animation-fill-mode: both;      animation-timeline: --compare-grip;      animation-range: contain;      &:dir(rtl) {        animation-direction: reverse;      }    }    .compare-range {      overflow: hidden;      &::-webkit-slider-thumb {        view-timeline: --compare-grip inline;      }    }  }}@keyframes compare-position {  from {    --compare-position: 100%;  }  to {    --compare-position: 0%;  }}