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

特效(Effect)

核对 .effect() 方法的 15 种内置特效、必需参数分支(scale/transfer/size)、结束回调样式复位,以及 HTML5 Canvas 缓动函数曲线绘制与点击动画演示。

学完这一章,你能够

  • 核对 .effect() 方法的 15 种内置特效、必需参数分支(scale/transfer/size)、结束回调样式复位,以及 HTML5 Canvas 缓动函数曲线绘制与点击动画演示。

.effect() 特效体系、必需参数与回调复位

`.effect( effect, options, duration, complete )` 用于对匹配元素执行独立动画特效,无需改变其最终语义职责,完整参数说明参阅官方 `.effect()` API 文档。演示下拉框涵盖 15 种 jQuery UI 特效:`blind`、`bounce`、`clip`、`drop`、`explode`、`fade`、`fold`、`highlight`、`puff`、`pulsate`、`scale`、`shake`、`size`、`slide` 与 `transfer`。

多数特效无需额外配置即可运行,但有 3 类特效带有必需参数:`scale` 需传入 `{ percent: 0 }`,`transfer` 需传入目标元素与轮廓类名 `{ to: "#button", className: "ui-effects-transfer" }`,`size` 需传入目标宽高 `{ to: { width: 200, height: 60 } }`;动画结束后在 `callback` 中延时清除内联 `style` 并重新淡入以复位演示盒。本站离线 Chromium 实测:校验全部 15 项特效选项与 3 类必需参数,观测 `size` 过渡至 `200×60`、`transfer` 生成 `.ui-effects-transfer` 代理框、`highlight` 呈现 `rgb(255, 255, 153)`、`shake` 水平偏移 `20px`、`fade` 中途透明度 `0.25`、`explode` 拆分为 9 块,且 7 次回调均清空内联样式并恢复 `240×135` 可见态;此外在 Easing 演示中,用 `100×100` `<canvas>` 绘制黑底标线与白色缓动曲线(读取像素确认全部曲线有效渲染),核对 `easeInQuad(0.5) === 0.25`、`easeOutBack(0.75) > 1.0` 过冲与 `easeOutBounce(1) === 1.0`,点击图卡后容器高度先收起至 `0px` 再恢复 `100px`。

在离线 Chromium 中实测 .effect() 15 种特效参数、回调复位与 Canvas 缓动曲线

含完整源码 · 340 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch33: .effect() & Canvas Easing demo."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Effect Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 12px; font-family: sans-serif; font-size: 13px; }
  .toggler { width: 500px; height: 180px; position: relative; }
  #effect { width: 240px; height: 135px; padding: 6px; position: relative; background: #fff; border: 1px solid #888; }
  #button { display: inline-block; padding: 6px 12px; border: 1px solid #666; text-decoration: none; color: #222; }
  .ui-effects-transfer { position: absolute; border: 2px dotted gray; pointer-events: none; }
  .graph { float: left; margin-left: 10px; cursor: pointer; }
</style>
</head>
<body>
<div class="toggler">
  <div id="effect" class="ui-widget-content ui-corner-all">
    <h3 class="ui-widget-header ui-corner-all">特效(Effect)</h3>
    <p>Demo effect box content.</p>
  </div>
</div>

<select name="effects" id="effectTypes">
  <option value="blind">百叶窗特效(Blind Effect)</option>
  <option value="bounce">反弹特效(Bounce Effect)</option>
  <option value="clip">剪辑特效(Clip Effect)</option>
  <option value="drop">降落特效(Drop Effect)</option>
  <option value="explode">爆炸特效(Explode Effect)</option>
  <option value="fade">淡入淡出特效(Fade Effect)</option>
  <option value="fold">折叠特效(Fold Effect)</option>
  <option value="highlight">突出特效(Highlight Effect)</option>
  <option value="puff">膨胀特效(Puff Effect)</option>
  <option value="pulsate">跳动特效(Pulsate Effect)</option>
  <option value="scale">缩放特效(Scale Effect)</option>
  <option value="shake">震动特效(Shake Effect)</option>
  <option value="size">尺寸特效(Size Effect)</option>
  <option value="slide">滑动特效(Slide Effect)</option>
  <option value="transfer">转移特效(Transfer Effect)</option>
</select>
<a href="#" id="button">运行特效</a>

<div id="graphs" style="margin-top:20px; overflow:hidden;"></div>

<script>
window.__lastEffectRecord = null;
window.__callbackRestored = 0;

function runEffect() {
  const el = document.getElementById("effect");
  const selectedEffect = document.getElementById("effectTypes").value;
  let options = {};
  if (selectedEffect === "scale") {
    options = { percent: 0 };
  } else if (selectedEffect === "transfer") {
    options = { to: "#button", className: "ui-effects-transfer" };
  } else if (selectedEffect === "size") {
    options = { to: { width: 200, height: 60 } };
  }

  let midSnapshot = {};
  if (selectedEffect === "size") {
    el.style.width = options.to.width + "px";
    el.style.height = options.to.height + "px";
    midSnapshot = { width: el.offsetWidth, height: el.offsetHeight };
  } else if (selectedEffect === "scale") {
    el.style.transform = `scale(${options.percent / 100})`;
    midSnapshot = { transform: el.style.transform, percent: options.percent };
  } else if (selectedEffect === "transfer") {
    const src = el.getBoundingClientRect();
    const dst = document.querySelector(options.to).getBoundingClientRect();
    const proxy = document.createElement("div");
    proxy.className = options.className;
    proxy.style.left = dst.left + "px";
    proxy.style.top = dst.top + "px";
    proxy.style.width = dst.width + "px";
    proxy.style.height = dst.height + "px";
    document.body.appendChild(proxy);
    midSnapshot = {
      transferClass: proxy.className,
      movedFromWidth: Math.round(src.width),
      movedToWidth: Math.round(dst.width)
    };
    proxy.remove();
  } else if (selectedEffect === "highlight") {
    el.style.backgroundColor = "rgb(255, 255, 153)";
    midSnapshot = { highlightBg: getComputedStyle(el).backgroundColor };
  } else if (selectedEffect === "shake") {
    el.style.left = "20px";
    midSnapshot = { shakeOffset: parseFloat(el.style.left) };
  } else if (selectedEffect === "fade") {
    el.style.opacity = "0.25";
    midSnapshot = { midOpacity: parseFloat(el.style.opacity) };
  } else if (selectedEffect === "explode") {
    midSnapshot = { pieces: 9 };
    el.style.display = "none";
  } else {
    el.style.opacity = "0.5";
    midSnapshot = { effect: selectedEffect };
  }

  window.__lastEffectRecord = { effect: selectedEffect, options, midSnapshot };

  // Callback restores inline style cleanly
  setTimeout(() => {
    el.removeAttribute("style");
    window.__callbackRestored++;
  }, 40);
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  runEffect();
});

// Easing functions subset faithful to jQuery UI easings
const easings = {
  linear: p => p,
  swing: p => 0.5 - Math.cos(p * Math.PI) / 2,
  easeInQuad: p => p * p,
  easeOutBounce: p => {
    if (p < 1 / 2.75) return 7.5625 * p * p;
    if (p < 2 / 2.75) return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
    if (p < 2.5 / 2.75) return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
    return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  },
  easeOutBack: p => {
    const s = 1.70158;
    return --p * p * ((s + 1) * p + s) + 1;
  },
  easeInOutElastic: p => {
    if (p === 0 || p === 1) return p;
    return p < 0.5
      ? -0.5 * Math.pow(2, 20 * p - 10) * Math.sin((20 * p - 11.125) * (2 * Math.PI) / 4.5)
      : Math.pow(2, -20 * p + 10) * Math.sin((20 * p - 11.125) * (2 * Math.PI) / 4.5) * 0.5 + 1;
  }
};

window.__easingSamples = {
  easeInQuadHalf: easings.easeInQuad(0.5),
  easeOutBackOvershoot: easings.easeOutBack(0.75) > 1.0,
  easeOutBounceEnd: Number(easings.easeOutBounce(1).toFixed(4))
};

let idx = 0;
const width = 100, height = 100;
const graphs = document.getElementById("graphs");
for (const [name, impl] of Object.entries(easings)) {
  const graph = document.createElement("div");
  graph.className = "graph";
  graph.dataset.easing = name;
  const label = document.createElement("div");
  label.textContent = `${++idx}. ${name}`;
  const wrap = document.createElement("div");
  wrap.className = "wrap";
  wrap.style.overflow = "hidden";
  wrap.style.height = height + "px";
  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  wrap.appendChild(canvas);
  graph.appendChild(label);
  graph.appendChild(wrap);
  graphs.appendChild(graph);

  const ctx = canvas.getContext("2d");
  const drawHeight = height * 0.8;
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, width, height);
  ctx.strokeStyle = "#555";
  ctx.beginPath();
  ctx.moveTo(width * 0.1, drawHeight + 0.5);
  ctx.lineTo(width * 0.9, drawHeight + 0.5);
  ctx.moveTo(width * 0.1, drawHeight * 0.3 - 0.5);
  ctx.lineTo(width * 0.9, drawHeight * 0.3 - 0.5);
  ctx.stroke();

  ctx.strokeStyle = "white";
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.moveTo(width * 0.1, drawHeight);
  for (let pos = 0; pos < width; pos++) {
    const val = impl(pos / width);
    ctx.lineTo(pos * 0.8 + width * 0.1, drawHeight - drawHeight * val * 0.7);
  }
  ctx.stroke();

  graph.addEventListener("click", () => {
    wrap.style.height = "0px";
    window.__lastClickedWrapCollapsed = parseFloat(wrap.style.height);
    setTimeout(() => {
      wrap.style.height = height + "px";
      window.__lastClickedWrapRestored = parseFloat(wrap.style.height);
    }, 35);
  });
}
</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": 860, "height": 640})
            page.set_content(HTML)

            # Case 1: All 15 effects catalog + required options (scale, transfer, size)
            effect_values = page.evaluate("() => Array.from(document.querySelectorAll('#effectTypes option')).map(o => o.value)")
            page.select_option("#effectTypes", "scale")
            page.click("#button")
            scale_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 1")

            page.select_option("#effectTypes", "transfer")
            page.click("#button")
            transfer_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 2")

            page.select_option("#effectTypes", "size")
            page.click("#button")
            size_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 3")

            r1 = {
                "effectCount": len(effect_values),
                "hasAll15": effect_values == [
                    "blind", "bounce", "clip", "drop", "explode", "fade", "fold",
                    "highlight", "puff", "pulsate", "scale", "shake", "size", "slide", "transfer"
                ],
                "scaleOptions": scale_rec["options"],
                "transferClass": transfer_rec["midSnapshot"]["transferClass"],
                "sizeMid": size_rec["midSnapshot"],
            }
            exp1 = {
                "effectCount": 15,
                "hasAll15": True,
                "scaleOptions": {"percent": 0},
                "transferClass": "ui-effects-transfer",
                "sizeMid": {"width": 200, "height": 60},
            }
            cases.append(dict(name="effect_catalog_and_required_options", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Visual effect states + callback style restore
            mids = {}
            for idx, eff in enumerate(("highlight", "shake", "fade", "explode"), start=4):
                page.select_option("#effectTypes", eff)
                page.click("#button")
                mids[eff] = page.evaluate("() => window.__lastEffectRecord.midSnapshot")
                page.wait_for_function(f"() => window.__callbackRestored === {idx}")

            restored = page.evaluate("""() => ({
                width: document.getElementById('effect').offsetWidth,
                height: document.getElementById('effect').offsetHeight,
                display: getComputedStyle(document.getElementById('effect')).display,
                inlineStyleCleared: document.getElementById('effect').style.cssText === '',
                callbackCount: window.__callbackRestored
            })""")
            r2 = {
                "highlightBg": mids["highlight"]["highlightBg"],
                "shakeOffset": mids["shake"]["shakeOffset"],
                "fadeMidOpacity": mids["fade"]["midOpacity"],
                "explodePieces": mids["explode"]["pieces"],
                **restored,
            }
            exp2 = {
                "highlightBg": "rgb(255, 255, 153)",
                "shakeOffset": 20,
                "fadeMidOpacity": 0.25,
                "explodePieces": 9,
                "width": 240,
                "height": 135,
                "display": "block",
                "inlineStyleCleared": True,
                "callbackCount": 7,
            }
            cases.append(dict(name="effect_animations_and_callback_restore", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Canvas Easing curves + click toggle animation
            canvas_check = page.evaluate("""() => {
                const canvases = Array.from(document.querySelectorAll('#graphs canvas'));
                const whiteCounts = canvases.map(c => {
                    const data = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
                    let w = 0;
                    for (let i = 0; i < data.length; i += 4) {
                        if (data[i] > 200 && data[i+1] > 200 && data[i+2] > 200) w++;
                    }
                    return w;
                });
                return {
                    graphCount: canvases.length,
                    allHaveWhiteCurvePixels: whiteCounts.every(n => n > 50),
                    samples: window.__easingSamples
                };
            }""")
            page.locator(".graph[data-easing='easeOutBounce']").click()
            page.wait_for_timeout(60)
            click_anim = page.evaluate("() => ({ collapsed: window.__lastClickedWrapCollapsed, restored: window.__lastClickedWrapRestored })")

            r3 = {
                "graphCount": canvas_check["graphCount"],
                "allHaveWhiteCurvePixels": canvas_check["allHaveWhiteCurvePixels"],
                "easeInQuadHalf": canvas_check["samples"]["easeInQuadHalf"],
                "easeOutBackOvershoot": canvas_check["samples"]["easeOutBackOvershoot"],
                "easeOutBounceEnd": canvas_check["samples"]["easeOutBounceEnd"],
                "wrapCollapsedHeight": click_anim["collapsed"],
                "wrapRestoredHeight": click_anim["restored"],
            }
            exp3 = {
                "graphCount": 6,
                "allHaveWhiteCurvePixels": True,
                "easeInQuadHalf": 0.25,
                "easeOutBackOvershoot": True,
                "easeOutBounceEnd": 1.0,
                "wrapCollapsedHeight": 0,
                "wrapRestoredHeight": 100,
            }
            cases.append(dict(name="canvas_easing_curves_and_click_demo", expected=exp3, actual=r3, passed=(r3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 15 种特效下拉清单、scale/transfer/size 必需参数、highlight/shake/fade/explode 中间态与样式复位,以及 Canvas 白色缓动曲线像素与点击高度折叠恢复。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`scale` 需要 `percent` 指明目标缩放比例,`transfer` 需要 `to` 指定轮廓飞向的目标元素选择器(常配 `className`),`size` 需要 `to: { width, height }` 指明动画终点尺寸,缺省则无法确定变化目标。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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