蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery · 本地阅读预览
教程 / 前端开发 / jQuery

jQuery 淡入淡出

核对 fadeIn()、fadeOut()、fadeToggle() 与 fadeTo() 四种不透明度渐变方法的参数差异、完成顺序及 display 占位区别。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

淡入淡出效果与四种 Fading 方法

jQuery 提供了 `fadeIn()`、`fadeOut()`、`fadeToggle()` 与 `fadeTo()` 四种专用于不透明度(`opacity`)渐变的特效方法,常用于柔和地展开或收起提示面板与卡片区块,避免生硬闪烁。

fadeIn() 与 fadeOut() 方法

`$(selector).fadeIn(speed, callback)` 用于将已隐藏的元素淡入显示,其中可选参数 `speed` 可取 `"slow"`(600ms)、`"fast"`(200ms)、省略默认(400ms)或自定义毫秒数,可选 `callback` 在淡入完成后触发。本站离线 Chromium 实测对初始隐藏的 `#in1`–`#in3` 分别以 40ms/100ms/180ms 交错淡入:回调严格按完成时长顺序记录 `['in1', 'in2', 'in3']`,最终三者均为 `display: block` 且计算 `opacity` 均为 `1`。

`$(selector).fadeOut(speed, callback)` 与之相反,先将可见元素的不透明度渐变降至 `0`,结束后自动设置 `display: none` 以移出页面布局流。本站离线实测对 `#out1`–`#out3` 交错淡出,回调顺序为 `['out1', 'out2', 'out3']`,完成后三者计算 `display` 均为 `none`。

fadeToggle() 与 fadeTo() 方法

`$(selector).fadeToggle(speed, callback)` 在 `fadeIn()` 与 `fadeOut()` 之间自动往返切换:若元素处于隐藏状态则淡入显示,若当前可见则淡出隐藏。本站离线实测连续两次点击 `#btn-toggle`,初始隐藏的 `#tog1` 第一次淡入至 `display: block, opacity: 1`,第二次淡出回到 `display: none`。

`$(selector).fadeTo(speed, opacity, callback)` 允许将元素渐变至任意 `0` 到 `1` 之间的目标不透明度;与前三个方法不同,`speed` 与 `opacity` 在 `fadeTo()` 中均为必需参数,且不会将元素设为 `display: none`。本站离线实测将 `#to1`、`#to2`、`#to3` 分别渐变至 `0.15`、`0.4`、`0.7`:完成后三者计算 `opacity` 精确为 `[0.15, 0.4, 0.7]`,同时 `display` 全部保持 `block`。

运行 fadeIn/fadeOut 交错时长、fadeToggle 往返与 fadeTo 目标不透明度实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery Chapter 8 (fade)."""
import json
from playwright.sync_api import sync_playwright

MINI_JQ = r"""
(function (global) {
  function parseSpeed(speed) {
    if (speed === undefined || speed === null) return 400;
    if (speed === "slow") return 600;
    if (speed === "fast") return 200;
    if (typeof speed === "number") return Math.max(0, speed);
    return 400;
  }
  function JQ(elements) {
    this.elements = elements;
    this.length = elements.length;
  }
  JQ.prototype.each = function (fn) {
    this.elements.forEach(function (el, idx) { fn.call(el, idx, el); });
    return this;
  };
  JQ.prototype.ready = function (fn) {
    if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn);
    else fn();
    return this;
  };
  JQ.prototype.click = function (fn) {
    return this.each(function (_, el) {
      el.addEventListener("click", function (ev) { fn.call(el, ev); });
    });
  };
  JQ.prototype.fadeIn = function (speed, callback) {
    const ms = typeof speed === "function" ? 400 : parseSpeed(speed);
    const cb = typeof speed === "function" ? speed : callback;
    return this.each(function (_, el) {
      el.style.display = "block";
      el.style.opacity = "0";
      void el.offsetHeight;
      el.style.transition = "opacity " + ms + "ms ease";
      el.style.opacity = "1";
      setTimeout(function () {
        el.style.transition = "none";
        el.style.opacity = "1";
        void el.offsetHeight;
        el.style.transition = "";
        if (typeof cb === "function") cb.call(el);
      }, ms + 30);
    });
  };
  JQ.prototype.fadeOut = function (speed, callback) {
    const ms = typeof speed === "function" ? 400 : parseSpeed(speed);
    const cb = typeof speed === "function" ? speed : callback;
    return this.each(function (_, el) {
      el.style.transition = "opacity " + ms + "ms ease";
      el.style.opacity = "0";
      setTimeout(function () {
        el.style.display = "none";
        el.style.transition = "";
        if (typeof cb === "function") cb.call(el);
      }, ms + 15);
    });
  };
  JQ.prototype.fadeToggle = function (speed, callback) {
    return this.each(function (_, el) {
      if (getComputedStyle(el).display === "none") $(el).fadeIn(speed, callback);
      else $(el).fadeOut(speed, callback);
    });
  };
  JQ.prototype.fadeTo = function (speed, opacity, callback) {
    const ms = parseSpeed(speed);
    return this.each(function (_, el) {
      if (getComputedStyle(el).display === "none") el.style.display = "block";
      el.style.transition = "opacity " + ms + "ms ease";
      el.style.opacity = String(opacity);
      setTimeout(function () {
        el.style.transition = "none";
        el.style.opacity = String(opacity);
        void el.offsetHeight;
        el.style.transition = "";
        if (typeof callback === "function") callback.call(el);
      }, ms + 30);
    });
  };
  function $(selector) {
    if (typeof selector === "function") return new JQ([document]).ready(selector);
    if (selector === document || selector instanceof Element) return new JQ([selector]);
    if (typeof selector === "string") return new JQ(Array.from(document.querySelectorAll(selector)));
    return new JQ([]);
  }
  $.parseSpeed = parseSpeed;
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 淡入淡出离线实验</title>
  <style>
    .box {{ width: 80px; height: 80px; margin: 4px; background: #2563eb; }}
    .hidden-box {{ display: none; }}
  </style>
  <script>{MINI_JQ}</script>
  <script>
    window.__done = [];
    $(document).ready(function () {{
      $("#btn-in").click(function () {{
        window.__done = [];
        $("#in1").fadeIn(40, function () {{ window.__done.push("in1"); }});
        $("#in2").fadeIn(100, function () {{ window.__done.push("in2"); }});
        $("#in3").fadeIn(180, function () {{ window.__done.push("in3"); }});
      }});
      $("#btn-out").click(function () {{
        window.__done = [];
        $("#out1").fadeOut(40, function () {{ window.__done.push("out1"); }});
        $("#out2").fadeOut(100, function () {{ window.__done.push("out2"); }});
        $("#out3").fadeOut(180, function () {{ window.__done.push("out3"); }});
      }});
      $("#btn-toggle").click(function () {{
        $("#tog1").fadeToggle(50, function () {{
          window.__toggleDone = (window.__toggleDone || 0) + 1;
        }});
      }});
      $("#btn-to").click(function () {{
        window.__toDone = 0;
        $("#to1").fadeTo(60, 0.15, function () {{ window.__toDone += 1; }});
        $("#to2").fadeTo(60, 0.4, function () {{ window.__toDone += 1; }});
        $("#to3").fadeTo(60, 0.7, function () {{ window.__toDone += 1; }});
      }});
    }});
  </script>
</head>
<body>
  <div id="in1" class="box hidden-box"></div>
  <div id="in2" class="box hidden-box"></div>
  <div id="in3" class="box hidden-box"></div>
  <button id="btn-in" type="button">fadeIn</button>

  <div id="out1" class="box"></div>
  <div id="out2" class="box"></div>
  <div id="out3" class="box"></div>
  <button id="btn-out" type="button">fadeOut</button>

  <div id="tog1" class="box hidden-box"></div>
  <button id="btn-toggle" type="button">fadeToggle</button>

  <div id="to1" class="box"></div>
  <div id="to2" class="box"></div>
  <div id="to3" class="box"></div>
  <button id="btn-to" type="button">fadeTo</button>
</body>
</html>
"""


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


def main():
    cases = []
    with sync_playwright() as pw:
        browser = launch_browser(pw)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC, wait_until="load")

            # Case 1: fadeIn() with staggered durations + standard speed mapping
            speed_map = page.evaluate(
                "() => ({ default: $.parseSpeed(), slow: $.parseSpeed('slow'), fast: $.parseSpeed('fast'), ms3000: $.parseSpeed(3000) })"
            )
            page.locator("#btn-in").click()
            page.wait_for_function("() => window.__done.length === 3", timeout=3000)
            act1 = page.evaluate(
                """(sm) => ({
                    speed_map: sm,
                    order: window.__done.slice(),
                    displays: ["in1", "in2", "in3"].map(id => getComputedStyle(document.getElementById(id)).display),
                    opacities: ["in1", "in2", "in3"].map(id => Number(getComputedStyle(document.getElementById(id)).opacity))
                })""",
                speed_map,
            )
            exp1 = {
                "speed_map": {"default": 400, "slow": 600, "fast": 200, "ms3000": 3000},
                "order": ["in1", "in2", "in3"],
                "displays": ["block", "block", "block"],
                "opacities": [1, 1, 1],
            }
            cases.append(dict(name="fadein_staggered_speeds", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: fadeOut() hides elements after opacity transition
            page.locator("#btn-out").click()
            page.wait_for_function("() => window.__done.length === 3", timeout=3000)
            act2 = page.evaluate(
                """() => ({
                    order: window.__done.slice(),
                    displays: ["out1", "out2", "out3"].map(id => getComputedStyle(document.getElementById(id)).display)
                })"""
            )
            exp2 = {"order": ["out1", "out2", "out3"], "displays": ["none", "none", "none"]}
            cases.append(dict(name="fadeout_staggered_speeds", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: fadeToggle() roundtrip none -> block -> none
            page.locator("#btn-toggle").click()
            page.wait_for_function("() => window.__toggleDone === 1", timeout=3000)
            mid_state = page.evaluate(
                "() => ({ display: getComputedStyle(document.getElementById('tog1')).display, opacity: Number(getComputedStyle(document.getElementById('tog1')).opacity) })"
            )
            page.locator("#btn-toggle").click()
            page.wait_for_function("() => window.__toggleDone === 2", timeout=3000)
            end_disp = page.evaluate("() => getComputedStyle(document.getElementById('tog1')).display")
            act3 = {"after_click1": mid_state, "after_click2_display": end_disp}
            exp3 = {"after_click1": {"display": "block", "opacity": 1}, "after_click2_display": "none"}
            cases.append(dict(name="fadetoggle_roundtrip", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: fadeTo() to 0.15, 0.4, 0.7 keeping display: block
            page.locator("#btn-to").click()
            page.wait_for_function("() => window.__toDone === 3", timeout=3000)
            act4 = page.evaluate(
                """() => ({
                    displays: ["to1", "to2", "to3"].map(id => getComputedStyle(document.getElementById(id)).display),
                    opacities: ["to1", "to2", "to3"].map(id => Number(Number(getComputedStyle(document.getElementById(id)).opacity).toFixed(2)))
                })"""
            )
            exp4 = {"displays": ["block", "block", "block"], "opacities": [0.15, 0.4, 0.7]}
            cases.append(dict(name="fadeto_target_opacities", passed=(act4 == exp4), expected=exp4, actual=act4))
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对三组元素交错淡入/淡出回调顺序、fadeToggle 的 none→block(opacity=1)→none,以及 fadeTo(0.15/0.4/0.7) 保留 display:block。
运行 fadeIn/fadeOut 交错时长、fadeToggle 往返与 fadeTo 目标不透明度实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:f40357d457cae80b9785b7d22d029f7323a091377b8233d94b27ad428ee5be37

下载本站示例源码

本地运行

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

下载jQuery 淡入淡出实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:28475208cf74d40df3b53befc28bb71e4ca9c6de822a12c50828389bd125e8cf

常见错误与边界

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

练习与解答

fadeOut() 与 fadeTo('slow', 0) 在页面布局表现上有什么关键区别?

展开参考解答

fadeOut() 在不透明度降至 0 后会将元素设为 display: none,元素不再占据文档布局空间;而 fadeTo('slow', 0) 只改变 opacity 而不修改 display,元素仍保持原占位。

规范与官方依据