CSS Transition 看似簡單,但各瀏覽器對規範的實作細節差異極大,導致 getComputedStyle() 讀取值異常、TransitionEnd 事件觸發不一致、縮寫屬性展開行為不同等坑。本文基於 2013 年主流瀏覽器(Firefox 18、Opera 12、IE10、Safari 6、Chrome 23)實測,整理關鍵差異與規避策略。
all:所有可動畫屬性皆過渡transition-* 一一對應transition-property: foobar, padding;
transition-duration: 1s, 2s;
| 瀏覽器 | 解析結果 |
|---|---|
| WebKit (Chrome/Safari) | 解析為 all(忽略未知屬性) |
| Firefox / Opera | 解析為 all, padding(保留未知屬性) |
→ 建議:只寫確定支援的屬性,避免自定屬性名
getComputedStyle 可讀到)0.01s 讀回為 0.009999999776482582scubic-bezier(x1,y1,x2,y2)、steps(n, start|end)、關鍵字(linear, ease 等)linear 計算值:規範為 cubic-bezier(0,0,1,1),WebKit 回傳 cubic-bezier(0.25,0.1,0.25,1)(即 ease)steps() 可做逐幀動畫(如打字機效果)規範僅說「每個完成過渡的屬性觸發一次事件」,未定義縮寫屬性如何展開。
.example { padding:1px; transition-property:padding; transition-duration:1s; }
.example:hover { padding:10px; }
| 瀏覽器 | 觸發 TransitionEnd 的 propertyName |
|---|---|
| Gecko / Trident / Presto | padding-top, padding-right, padding-bottom, padding-left |
| WebKit | padding(縮寫屬性本身) |
.example { padding:1px; transition-property:all, padding; transition-duration:1s; }
.example:hover { padding:10px; }
font-size, line-height(隱式繼承變化)transition-duration: 1s; transition-delay: -1s;
const fixed = Math.round(event.elapsedTime * 1000) / 1000;
WebKit/IE 觸發 background-position-x, background-position-y 而非 background-position。
word-spacing 規範可動畫,實際無瀏覽器支援margin-top 接受長度/百分比,但只有長度可動畫getComputedStyle() 讀取中間值:需用 requestAnimationFrame 輪詢(Opera 除外)transition-property,不用 allpadding-top 等)或接受 WebKit 差異TransitionEnd.propertyName 做精確邏輯,改用 animation + animationend 或 JS 狀態機elapsedTime 以 Math.round(v*1000)/1000 修正transition-delay;需「快進」效果請改用 animationwill-change,非必要不動畫 layout 屬性(width/height/top/left)Transition 適合「狀態切換的視覺平滑」,複雜序列、精確控制、跨瀏覽器一致性需求高時,請改用 Web Animations API 或 CSS Animation + JS 協調。