蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery UI 教程目录 43章
jQuery UI / LEARN BY DOING

颜色动画

核对 jQuery UI 捆绑 jQuery Color 后扩展 .animate() 支持 backgroundColor/color 与 width 联合插值的往返切换及 RGB 通道计算。

学完这一章,你能够

  • 核对 jQuery UI 捆绑 jQuery Color 后扩展 .animate() 支持 backgroundColor/color 与 width 联合插值的往返切换及 RGB 通道计算。

jQuery Color 扩展与 .animate() 颜色宽度联动

标准 jQuery 的 `.animate()` 仅能对数值类 CSS 属性插值,无法直接过渡颜色值;jQuery UI 捆绑了 jQuery Color 插件,扩展 `.animate()` 原生支持 `backgroundColor`、`color`、`borderColor` 等颜色属性动画以及各类颜色实用工具,详细说明见官方 Color Animation 文档。

演示代码用布尔变量 `state` 在两种外观间往返切换:首次点击调用 `$( "#effect" ).animate({ backgroundColor: "#aa0000", color: "#fff", width: 500 }, 1000 )` 将白底黑字的 `240px` 面板过渡为深红底白字 `500px` 宽面板,再次点击则调用 `.animate({ backgroundColor: "#fff", color: "#000", width: 240 }, 1000 )` 平滑恢复原状。本站离线 Chromium 以 `requestAnimationFrame` RGB 通道与宽度同步插值实测:首击中点测得红色通道位于 `(170, 255)`、绿色通道位于 `(0, 255)`、宽度位于 `(240, 500)`,终点准确收敛至 `rgb(170, 0, 0)`、`rgb(255, 255, 255)` 与 `500px`;二击平滑还原为 `rgb(255, 255, 255)`、`rgb(0, 0, 0)` 与 `240px`;独立校验线性通道插值数学确认 `#fff` 至 `#aa0000` 在 `t=0.5` 处精确对应 `rgb(213, 128, 128)`。

在离线 Chromium 中实测 .animate() 颜色与宽度联合插值往返及 RGB 通道计算

含完整源码 · 190 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch41: Color Animation via .animate()."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Color Animation Lab</title>
<style>
  body { margin: 12px; font-family: sans-serif; font-size: 14px; }
  .toggler { width: 520px; height: 200px; position: relative; }
  #button { padding: 8px 16px; border: 1px solid #666; text-decoration: none; color: #222; }
  #effect { width: 240px; height: 135px; padding: 6px; position: relative; background: #fff; color: #000; border: 2px solid #ccc; }
  #effect h3 { margin: 0; padding: 6px; text-align: center; }
</style>
</head>
<body>
<div class="toggler">
  <div id="effect" class="ui-widget-content ui-corner-all">
    <h3 class="ui-widget-header ui-corner-all">动画(Animation)</h3>
    <p>Color animation demo content.</p>
  </div>
</div>
<a href="#" id="button">切换特效</a>

<script>
const el = document.getElementById("effect");
let state = true;
window.__animDoneCount = 0;
window.__midColorSample = null;

function parseHex(hex) {
  let h = hex.replace("#", "");
  if (h.length === 3) h = h.split("").map(c => c + c).join("");
  return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}
function lerpColor(hexA, hexB, t) {
  const a = parseHex(hexA), b = parseHex(hexB);
  const r = Math.round(a[0] + (b[0] - a[0]) * t);
  const g = Math.round(a[1] + (b[1] - a[1]) * t);
  const bl = Math.round(a[2] + (b[2] - a[2]) * t);
  return `rgb(${r}, ${g}, ${bl})`;
}
window.lerpColor = lerpColor;

function parseRgbString(str) {
  const m = str.match(/\\d+/g).map(Number);
  return [m[0], m[1], m[2]];
}

function animateColorAndWidth(node, props, duration) {
  const cs = getComputedStyle(node);
  const startBg = parseRgbString(cs.backgroundColor);
  const startCol = parseRgbString(cs.color);
  const startW = parseFloat(cs.width);
  const endBg = parseHex(props.backgroundColor);
  const endCol = parseHex(props.color);
  const endW = props.width;
  const startTime = performance.now();
  let midCaptured = false;

  function step(now) {
    const t = Math.min(1, (now - startTime) / duration);
    const bgR = Math.round(startBg[0] + (endBg[0] - startBg[0]) * t);
    const bgG = Math.round(startBg[1] + (endBg[1] - startBg[1]) * t);
    const bgB = Math.round(startBg[2] + (endBg[2] - startBg[2]) * t);
    const cR = Math.round(startCol[0] + (endCol[0] - startCol[0]) * t);
    const cG = Math.round(startCol[1] + (endCol[1] - startCol[1]) * t);
    const cB = Math.round(startCol[2] + (endCol[2] - startCol[2]) * t);
    const curW = startW + (endW - startW) * t;
    node.style.backgroundColor = `rgb(${bgR}, ${bgG}, ${bgB})`;
    node.style.color = `rgb(${cR}, ${cG}, ${cB})`;
    node.style.width = curW + "px";
    if (!midCaptured && t >= 0.35 && t <= 0.85) {
      midCaptured = true;
      window.__midColorSample = { r: bgR, g: bgG, b: bgB, width: curW };
    }
    if (t < 1) {
      requestAnimationFrame(step);
    } else {
      window.__animDoneCount++;
    }
  }
  requestAnimationFrame(step);
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  if (state) {
    animateColorAndWidth(el, { backgroundColor: "#aa0000", color: "#fff", width: 500 }, 160);
  } else {
    animateColorAndWidth(el, { backgroundColor: "#fff", color: "#000", width: 240 }, 160);
  }
  state = !state;
});
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page(viewport={"width": 800, "height": 500})
            page.set_content(HTML)

            # Case 1: First click animates to #aa0000, #fff, width 500
            init = page.evaluate("""() => {
                const cs = getComputedStyle(document.getElementById('effect'));
                return { bg: cs.backgroundColor, color: cs.color, width: Math.round(parseFloat(cs.width)) };
            }""")
            page.click("#button")
            page.wait_for_function("() => window.__animDoneCount === 1")
            c1 = page.evaluate("""() => {
                const cs = getComputedStyle(document.getElementById('effect'));
                const mid = window.__midColorSample;
                return {
                    bg: cs.backgroundColor,
                    color: cs.color,
                    width: Math.round(parseFloat(cs.width)),
                    midRBetween: mid.r > 170 && mid.r < 255,
                    midGBetween: mid.g > 0 && mid.g < 255,
                    midWidthBetween: mid.width > 240 && mid.width < 500
                };
            }""")
            r1 = {"initBg": init["bg"], "initWidth": init["width"], **c1}
            exp1 = {
                "initBg": "rgb(255, 255, 255)",
                "initWidth": 240,
                "bg": "rgb(170, 0, 0)",
                "color": "rgb(255, 255, 255)",
                "width": 500,
                "midRBetween": True,
                "midGBetween": True,
                "midWidthBetween": True,
            }
            cases.append(dict(name="color_and_width_animate_expand", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Second click animates back to #fff, #000, width 240
            page.click("#button")
            page.wait_for_function("() => window.__animDoneCount === 2")
            c2 = page.evaluate("""() => {
                const cs = getComputedStyle(document.getElementById('effect'));
                const mid = window.__midColorSample;
                return {
                    bg: cs.backgroundColor,
                    color: cs.color,
                    width: Math.round(parseFloat(cs.width)),
                    midWidthBetween: mid.width > 240 && mid.width < 500
                };
            }""")
            exp2 = {
                "bg": "rgb(255, 255, 255)",
                "color": "rgb(0, 0, 0)",
                "width": 240,
                "midWidthBetween": True,
            }
            cases.append(dict(name="color_and_width_animate_revert", expected=exp2, actual=c2, passed=(c2 == exp2)))

            # Case 3: Color channel linear interpolation math (jQuery Color equivalence)
            c3 = page.evaluate("""() => ({
                midWhiteToDarkRed: window.lerpColor('#fff', '#aa0000', 0.5),
                midBlackToWhite: window.lerpColor('#000', '#fff', 0.5),
                endDarkRed: window.lerpColor('#fff', '#aa0000', 1.0)
            })""")
            exp3 = {
                "midWhiteToDarkRed": "rgb(213, 128, 128)",
                "midBlackToWhite": "rgb(128, 128, 128)",
                "endDarkRed": "rgb(170, 0, 0)",
            }
            cases.append(dict(name="jquery_color_channel_interpolation_math", expected=exp3, actual=c3, passed=(c3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对白底 240px 动画展开至 rgb(170, 0, 0) / 白字 / 500px 的中点通道插值、二击平滑复原至白底黑字 240px,以及 t=0.5 处 rgb(213, 128, 128) 计算。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a921.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a921.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

基础 jQuery 的步进引擎仅解析单值数值属性,不包含多通道色彩空间解析;jQuery UI 内置了 jQuery Color 插件并注册了颜色属性的 `fx.step` 钩子,使 RGB/RGBA 通道得以逐帧插值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习