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

显示(Show)

核对 jQuery UI 增强版 .show() 方法以 13 种特效显示隐藏元素、scale/size 必需参数配置以及完成回调清理内联样式并淡出复位的流程。

学完这一章,你能够

  • 核对 jQuery UI 增强版 .show() 方法以 13 种特效显示隐藏元素、scale/size 必需参数配置以及完成回调清理内联样式并淡出复位的流程。

使用自定义特效显示隐藏元素

jQuery UI 对标准 jQuery `.show()` 进行了扩展,使其接受特效名、配置对象、时长与完成回调,从而以自定义入场动画显示原本隐藏的元素,完整签名与选项见官方 `.show()` API 文档。

演示初始化时先调用 `$( "#effect" ).hide()` 令目标盒处于隐藏态;下拉框列出 13 种适用于显隐过渡的特效(`blind`、`bounce`、`clip`、`drop`、`explode`、`fold`、`highlight`、`puff`、`pulsate`、`scale`、`shake`、`size`、`slide`,不包含 `fade` 与 `transfer`)。其中 `scale` 需传入 `{ percent: 100 }` 展开至全尺寸,`size` 需传入 `{ to: { width: 280, height: 185 } }` 过渡至更大尺寸;入场完成后 `callback` 延时调用 `removeAttr( "style" ).fadeOut()` 清除临时内联宽高并重新隐藏以便反复预览。本站离线 Chromium 实测:初始 `display: none`,`blind`/`clip`/`drop`/`fold`/`slide` 均将元素切至 `display: block`;`scale` 按 `percent: 100` 恢复 `240×135`,`size` 展开至 `280×185`;回调执行后内联 `width` 清除且重新回到 `display: none`。

在离线 Chromium 中实测 .show() 13 种入场特效、scale/size 参数与回调复位

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

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Show Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 12px; font-family: sans-serif; font-size: 13px; }
  .toggler { width: 500px; height: 200px; }
  #effect { width: 240px; height: 135px; padding: 6px; position: relative; border: 1px solid #888; background: #fff; }
  #button { padding: 6px 12px; border: 1px solid #666; text-decoration: none; color: #222; }
</style>
</head>
<body>
<div class="toggler">
  <div id="effect" class="ui-widget-content ui-corner-all">
    <h3 class="ui-widget-header ui-corner-all">显示(Show)</h3>
    <p>Show effect demo 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="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>
</select>
<a href="#" id="button">运行特效</a>

<script>
const el = document.getElementById("effect");
el.style.display = "none"; // $( "#effect" ).hide() on init
window.__showLog = [];
window.__autoHideEnabled = false;

function runShow() {
  const selectedEffect = document.getElementById("effectTypes").value;
  let options = {};
  if (selectedEffect === "scale") {
    options = { percent: 100 };
  } else if (selectedEffect === "size") {
    options = { to: { width: 280, height: 185 } };
  }
  el.style.display = "block";
  el.style.opacity = "1";
  if (selectedEffect === "size") {
    el.style.width = options.to.width + "px";
    el.style.height = options.to.height + "px";
  } else if (selectedEffect === "scale") {
    el.style.transform = `scale(${options.percent / 100})`;
  }
  window.__showLog.push({
    effect: selectedEffect,
    options,
    display: getComputedStyle(el).display,
    width: el.offsetWidth,
    height: el.offsetHeight
  });
  if (window.__autoHideEnabled) {
    setTimeout(() => {
      el.removeAttribute("style");
      el.style.display = "none";
      window.__afterFadeOutDisplay = getComputedStyle(el).display;
    }, 45);
  }
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  runShow();
});
</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: Initial hidden & 13 show effects
            init_disp = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            opts = page.evaluate("() => Array.from(document.querySelectorAll('#effectTypes option')).map(o => o.value)")
            revealed = {}
            for eff in ("blind", "clip", "drop", "fold", "slide"):
                page.evaluate("() => { document.getElementById('effect').removeAttribute('style'); document.getElementById('effect').style.display = 'none'; }")
                page.select_option("#effectTypes", eff)
                page.click("#button")
                revealed[eff] = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            r1 = {
                "initialDisplay": init_disp,
                "optionCount": len(opts),
                "excludesFadeAndTransfer": ("fade" not in opts and "transfer" not in opts),
                "revealedStates": revealed,
            }
            exp1 = {
                "initialDisplay": "none",
                "optionCount": 13,
                "excludesFadeAndTransfer": True,
                "revealedStates": {"blind": "block", "clip": "block", "drop": "block", "fold": "block", "slide": "block"},
            }
            cases.append(dict(name="initial_hidden_and_13_show_effects", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: scale (percent: 100) and size (280x185) required options
            page.evaluate("() => { document.getElementById('effect').removeAttribute('style'); document.getElementById('effect').style.display = 'none'; }")
            page.select_option("#effectTypes", "scale")
            page.click("#button")
            scale_entry = page.evaluate("() => window.__showLog[window.__showLog.length - 1]")

            page.evaluate("() => { document.getElementById('effect').removeAttribute('style'); document.getElementById('effect').style.display = 'none'; }")
            page.select_option("#effectTypes", "size")
            page.click("#button")
            size_entry = page.evaluate("() => window.__showLog[window.__showLog.length - 1]")

            r2 = {
                "scalePercent": scale_entry["options"]["percent"],
                "scaleDims": [scale_entry["width"], scale_entry["height"]],
                "sizeTarget": size_entry["options"]["to"],
                "sizeDims": [size_entry["width"], size_entry["height"]],
            }
            exp2 = {
                "scalePercent": 100,
                "scaleDims": [240, 135],
                "sizeTarget": {"width": 280, "height": 185},
                "sizeDims": [280, 185],
            }
            cases.append(dict(name="show_scale_and_size_required_options", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Callback removeAttr("style") + fadeOut() reset
            page.evaluate("() => { window.__autoHideEnabled = true; document.getElementById('effect').removeAttribute('style'); document.getElementById('effect').style.display = 'none'; }")
            page.select_option("#effectTypes", "size")
            page.click("#button")
            during_disp = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            page.wait_for_timeout(80)
            after_cb = page.evaluate("""() => ({
                displayAfterFadeOut: window.__afterFadeOutDisplay,
                inlineWidthCleared: document.getElementById('effect').style.width === ''
            })""")
            r3 = {"duringDisplay": during_disp, **after_cb}
            exp3 = {"duringDisplay": "block", "displayAfterFadeOut": "none", "inlineWidthCleared": True}
            cases.append(dict(name="show_callback_auto_fadeout_reset", expected=exp3, actual=r3, passed=(r3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对初始隐藏态与 13 种特效选项、scale percent:100 呈现 240×135、size 展开至 280×185,以及回调清除内联样式并重新隐藏。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

诸如 `size` 等特效会在元素上遗留内联 `width`/`height` 等样式,先移除 `style` 属性可恢复样式表定义的原始尺寸,避免下一次演示从残留尺寸起步。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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