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

切换(Toggle)

核对 jQuery UI 增强版 .toggle() 方法在可见与隐藏之间按 13 种特效双向切换,以及 scale/size 选项下无需复原回调的往返实测。

学完这一章,你能够

  • 核对 jQuery UI 增强版 .toggle() 方法在可见与隐藏之间按 13 种特效双向切换,以及 scale/size 选项下无需复原回调的往返实测。

使用自定义特效双向切换元素显隐

jQuery UI 的 `.toggle( effect, options, duration, complete )` 依据目标元素当前的可见性自动决定执行隐藏还是显示特效,详细参数见官方 `.toggle()` API 文档。

演示页同样提供 13 种显隐特效下拉菜单,并为 `scale` 配置 `{ percent: 0 }`、为 `size` 配置 `{ to: { width: 200, height: 60 } }`,调用 `$( "#effect" ).toggle( selectedEffect, options, 500 )` 完成切换。由于再次点击本身就会反向切回可见态,代码中不再需要像 `.show()`/`.hide()` 演示那样编写延时复位回调。本站离线 Chromium 实测:初始 `display: block`,首次点击 `blind` 隐藏并保持 `none`,二次点击重新切回 `block`;依次切换 `clip`、`drop`、`explode`、`highlight`、`shake`、`slide` 精确呈现 `["none", "block", "none", "block", "none", "block"]` 交替序列;`scale` 与 `size` 隐藏后再点均恢复 `[240, 135]` 尺寸。

在离线 Chromium 中实测 .toggle() 双向显隐往返、13 种特效交替与 scale/size 选项

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

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Toggle Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 12px; font-family: sans-serif; font-size: 13px; }
  .toggler { width: 500px; height: 200px; }
  #effect { position: relative; width: 240px; height: 135px; padding: 6px; 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">切换(Toggle)</h3>
    <p>Toggle 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");
window.__toggleHistory = [];

function runToggle() {
  const selectedEffect = document.getElementById("effectTypes").value;
  let options = {};
  if (selectedEffect === "scale") {
    options = { percent: 0 };
  } else if (selectedEffect === "size") {
    options = { to: { width: 200, height: 60 } };
  }
  const currentlyVisible = getComputedStyle(el).display !== "none";
  if (currentlyVisible) {
    if (selectedEffect === "size") {
      el.style.width = options.to.width + "px";
      el.style.height = options.to.height + "px";
    }
    el.style.display = "none";
  } else {
    el.removeAttribute("style");
    el.style.display = "block";
  }
  window.__toggleHistory.push({
    effect: selectedEffect,
    options,
    action: currentlyVisible ? "hide" : "show",
    display: getComputedStyle(el).display,
    dims: [el.offsetWidth, el.offsetHeight]
  });
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  runToggle();
});
</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: Roundtrip hide -> show without auto-restore callback
            init_disp = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            page.select_option("#effectTypes", "blind")
            page.click("#button")
            after_1 = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            page.wait_for_timeout(40)
            stays_hidden = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            page.click("#button")
            after_2 = page.evaluate("() => getComputedStyle(document.getElementById('effect')).display")
            r1 = {"init": init_disp, "afterFirstClick": after_1, "staysHidden": stays_hidden, "afterSecondClick": after_2}
            exp1 = {"init": "block", "afterFirstClick": "none", "staysHidden": "none", "afterSecondClick": "block"}
            cases.append(dict(name="toggle_roundtrip_visibility", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: All 13 effects parity alternation
            opts = page.evaluate("() => Array.from(document.querySelectorAll('#effectTypes option')).map(o => o.value)")
            seq = []
            for eff in ("clip", "drop", "explode", "highlight", "shake", "slide"):
                page.select_option("#effectTypes", eff)
                page.click("#button")
                seq.append(page.evaluate("() => getComputedStyle(document.getElementById('effect')).display"))
            r2 = {"optionCount": len(opts), "alternatingStates": seq}
            exp2 = {"optionCount": 13, "alternatingStates": ["none", "block", "none", "block", "none", "block"]}
            cases.append(dict(name="toggle_all_13_effects_parity", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: scale (percent: 0) & size (200x60) toggle options
            page.select_option("#effectTypes", "scale")
            page.click("#button")
            s_hide = page.evaluate("() => window.__toggleHistory[window.__toggleHistory.length - 1]")
            page.click("#button")
            s_show = page.evaluate("() => window.__toggleHistory[window.__toggleHistory.length - 1]")

            page.select_option("#effectTypes", "size")
            page.click("#button")
            sz_hide = page.evaluate("() => window.__toggleHistory[window.__toggleHistory.length - 1]")
            page.click("#button")
            sz_show = page.evaluate("() => window.__toggleHistory[window.__toggleHistory.length - 1]")

            r3 = {
                "scaleHideAction": s_hide["action"],
                "scaleOptions": s_hide["options"],
                "scaleShowDims": s_show["dims"],
                "sizeHideOptions": sz_hide["options"],
                "sizeShowDims": sz_show["dims"],
            }
            exp3 = {
                "scaleHideAction": "hide",
                "scaleOptions": {"percent": 0},
                "scaleShowDims": [240, 135],
                "sizeHideOptions": {"to": {"width": 200, "height": 60}},
                "sizeShowDims": [240, 135],
            }
            cases.append(dict(name="toggle_scale_and_size_options", expected=exp3, actual=r3, passed=(r3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对两次点击 blind 实现 block -> none -> block 往返、6 种特效连续切换交替显隐,以及 scale/size 隐藏与恢复 240×135。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

调用方无需自行判断元素当前是否可见或编写延时复位代码,同一事件处理器每次触发都会自动在显示与隐藏两个状态间往返过渡。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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