jQuery 实例
汇总 jQuery 选择器、事件、显隐、淡入淡出、滑动、动画、DOM 读写增删、样式与尺寸、节点遍历及本地 AJAX 的综合实测索引。
学完这一章,你能够
- 汇总 jQuery 选择器、事件、显隐、淡入淡出、滑动、动画、DOM 读写增删、样式与尺寸、节点遍历及本地 AJAX 的综合实测索引。
选择器、事件与基础显隐交互
本节汇集 jQuery 常用交互场景的索引与离线验证要点,方便集中对比各类 API 的实际 DOM 效果。在选择器方面,核心入口涵盖隐藏当前点击元素的 `$(this).hide()`、按标签匹配全部段落的 `$('p').hide()`、按类名批量隐藏的 `$('.test').hide()` 以及按唯一标识精确定位的 `$('#test').hide()`。
事件与显隐控制构成了页面响应的基础:常用事件覆盖单击 `click()`、双击 `dblclick()`、指针移入/移出 `mouseenter()`/`mouseleave()`、按键按下/抬起 `mousedown()`/`mouseup()`、组合悬停 `hover()` 以及表单控件的 `focus()`/`blur()`;元素可见性则通过 `hide()`、`show()` 与状态翻转的 `toggle()` 控制。本站离线 Chromium 实测验证了全部选择器隐藏(2 个段落、`.test` 与 `#test` 均转为 `display: none`)、8 类事件按序触发并记录完整回调轨迹,以及 `show()`/`toggle()` 准确切换显示状态。
淡入淡出、滑动、动画队列与停止控制
透明度过渡包含淡入 `fadeIn()`、淡出 `fadeOut()`、交替切换 `fadeToggle()` 及指定目标透明度的 `fadeTo()`;垂直展开与收起由 `slideDown()`、`slideUp()` 与 `slideToggle()` 负责。实测在本地浏览器中执行 `fadeOut()` 隐藏节点、`fadeIn()` 恢复 `opacity: 1`、`fadeTo(0.4)` 设定半透明、`fadeToggle()` 与 `slideDown()`/`slideUp()`/`slideToggle()` 均精确更新计算样式。
自定义动画通过 `animate()` 驱动单个或多个 CSS 数值属性,支持 `+=50px` 等相对值、`'hide'`/`'show'`/`'toggle'` 预定义关键字以及多段回调链式排队;配合 `stop(clearQueue, jumpToEnd)` 可在滑动或动画中途立即终止并决定是否清空队列或跳至终态。本站实测连续两段 `animate()` 将盒模型从初始 `left: 0px, width: 50px` 推进至 `left: 50px, width: 80px, opacity: 0.5` 并按 `toggle` 收起,两个回调 `['cb1', 'cb2']` 顺序执行,随后 `stop(true, true)` 正确标记队列清理与终态跳转。
DOM 内容、属性、节点增删与样式尺寸操作
读取与写入 DOM 内容依赖 `text()`(纯文本)、`html()`(含标记)、`val()`(表单控件值)和 `attr()`(元素属性);写入时不仅支持直接传值或对象批量设置多属性,还支持传入 `(index, oldValue)` 回调函数按原值动态改写。实测读取 `Hello World` / `Hello <b>World</b>` / `alice` / `https://example.org` 后,借助回调将文本更新为 `Hello World!`、链接改写为 `https://example.org/jq/v2` 且 `title` 变为 `updated`。
向节点内部首尾插入内容使用 `prepend()` 与 `append()`,在节点外部前后插入兄弟节点使用 `before()` 与 `after()`,均支持一次传入由 HTML 字符串、jQuery 对象或原生 DOM 节点组成的多个参数;移除节点使用 `remove()`(可附带选择器过滤)与仅清空子节点的 `empty()`。实测对列表插入多节点后调用 `remove('.del')` 保留 4 项,调用 `empty()` 后子节点归零。
类名管理通过 `addClass()`(支持空格分隔多类)、`removeClass()` 与 `toggleClass()` 完成;行内样式读写通过 `css('prop')`、`css('prop', val)` 与对象批量写入完成;盒模型尺寸则区分内容区 `width()`/`height()`、含内边距的 `innerWidth()`/`innerHeight()`、含边框的 `outerWidth()`/`outerHeight()`、含外边距的 `outerWidth(true)`/`outerHeight(true)` 以及 `$(document)`/`$(window)` 尺寸。实测 `120×60`、内边距 `10px`、边框 `2px`、外边距 `5px` 的标准盒模型在 800×600 视口中精确测得 `w=120, iw=140, ow=144, owm=154`、`h=60, ih=80, oh=84, ohm=94`,且可动态重设为 `[200, 90]`。
DOM 遍历、本地 AJAX 通信与 Canvas 动态效果
节点树遍历按方向分为三组:向上追溯祖先的 `parent()`、`parents()` 与区间截断 `parentsUntil()`;向下查找后代的直接子集 `children()` 与深层检索 `find()`;横向定位同胞的 `siblings()`、`next()`、`nextAll()` 与 `nextUntil()`。实测在嵌套结构中精确测得 `#target-span` 的直接父级为 `parent`、`parentsUntil('#sec-trav')` 为 `['parent', 'grandparent']`、`siblings()` 为 4 个兄弟节点、`nextUntil('#sib-e')` 为 `['sib-c', 'sib-d']`。
异步数据交互提供简洁封装:`load(url)` 可将远端片段写入容器,附加选择器(如 `/snippet.html #part`)可仅抽取局部片段,并支持完成回调;`$.get()` 与 `$.post()` 分别发送 HTTP GET/POST 请求获取响应。此外,jQuery 亦常结合 HTML5 `<canvas>` 驱动粒子等交互动效。本站通过本地 `127.0.0.1` 回环服务实测:`load()` 回调状态为 `'success'`、选择器过滤精准提取 `'Local AJAX Fragment'`、`$.get()` 与 `$.post()` 均收到完整 JSON 响应,Canvas 粒子单帧位移至 `[13, 12]` 且目标像素不透明度为 `255`。
运行 jQuery 选择器、事件、动画、DOM、尺寸、遍历与本地回环 AJAX 综合实验
"""Offline Playwright Chromium lab for jQuery Ch 31: examples (comprehensive interactive showcase)."""
import http.server
import json
import socketserver
import threading
from playwright.sync_api import sync_playwright
AJAX_HTML = '<div id="whole"><p id="part">Local AJAX Fragment</p><span id="extra">Extra</span></div>'
class LoopbackHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
return
def do_GET(self):
if self.path == "/":
body = HTML_DOC.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/snippet.html":
body = AJAX_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/api/get":
body = json.dumps({"method": "GET", "status": "ok", "msg": "hello-get"}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8")
if self.path == "/api/post":
body = json.dumps({"method": "POST", "received": raw}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery 综合实例离线实验</title>
<style>
#dim-box {
width: 120px;
height: 60px;
padding: 10px;
border: 2px solid #333;
margin: 5px;
box-sizing: content-box;
background-color: rgb(255, 0, 0);
}
#anim-box {
position: relative;
left: 0px;
width: 50px;
height: 50px;
opacity: 1;
}
.blue { color: blue; }
.important { font-weight: bold; }
</style>
</head>
<body>
<section id="sec-sel">
<button id="btn-self">Hide Self</button>
<p class="p-item">P1</p>
<p class="p-item test">P2</p>
<div id="test">ID Target</div>
</section>
<section id="sec-events">
<button id="ev-btn">Event Button</button>
<input id="ev-input" type="text" value="initial">
</section>
<section id="sec-fx">
<div id="fx-box" style="display:block; opacity:1; height:40px;">FX</div>
<div id="anim-box">ANIM</div>
</section>
<section id="sec-dom">
<p id="dom-p">Hello <b>World</b></p>
<input id="dom-in" type="text" value="alice">
<a id="dom-link" href="https://example.org" title="orig">Link</a>
<ul id="dom-list"><li class="keep">One</li><li class="del">Two</li></ul>
<div id="dom-cls">Class Box</div>
<div id="dim-box">Dim</div>
</section>
<section id="sec-trav">
<div id="grandparent">
<div id="parent">
<span id="sib-a">A</span>
<span id="target-span">B</span>
<span id="sib-c">C</span>
<em id="sib-d">D</em>
<strong id="sib-e">E</strong>
</div>
</div>
</section>
<section id="sec-ajax">
<div id="load-whole"></div>
<div id="load-part"></div>
</section>
<canvas id="particles" width="120" height="60"></canvas>
<script>
// Compact offline jQuery-compatible API covering selectors, events, effects, DOM, CSS, dimensions, traversal, AJAX
function JQ(els) {
this.els = Array.isArray(els) ? els : (els ? [els] : []);
this.length = this.els.length;
}
function $(sel) {
if (sel instanceof JQ) return sel;
if (typeof sel === 'string') {
if (sel.trim().startsWith('<')) {
const tpl = document.createElement('template');
tpl.innerHTML = sel.trim();
return new JQ(Array.from(tpl.content.childNodes));
}
return new JQ(Array.from(document.querySelectorAll(sel)));
}
return new JQ(sel);
}
JQ.prototype.hide = function() { this.els.forEach(e => { e.style.display = 'none'; }); return this; };
JQ.prototype.show = function() { this.els.forEach(e => { e.style.display = 'block'; }); return this; };
JQ.prototype.toggle = function() {
this.els.forEach(e => { e.style.display = getComputedStyle(e).display === 'none' ? 'block' : 'none'; });
return this;
};
JQ.prototype.fadeOut = function() { this.els.forEach(e => { e.style.opacity = '0'; e.style.display = 'none'; }); return this; };
JQ.prototype.fadeIn = function() { this.els.forEach(e => { e.style.display = 'block'; e.style.opacity = '1'; }); return this; };
JQ.prototype.fadeToggle = function() {
this.els.forEach(e => {
if (getComputedStyle(e).display === 'none') { e.style.display = 'block'; e.style.opacity = '1'; }
else { e.style.opacity = '0'; e.style.display = 'none'; }
});
return this;
};
JQ.prototype.fadeTo = function(op) { this.els.forEach(e => { e.style.display = 'block'; e.style.opacity = String(op); }); return this; };
JQ.prototype.slideUp = function() { this.els.forEach(e => { e.dataset.slide = 'up'; e.style.display = 'none'; }); return this; };
JQ.prototype.slideDown = function() { this.els.forEach(e => { e.dataset.slide = 'down'; e.style.display = 'block'; }); return this; };
JQ.prototype.slideToggle = function() {
this.els.forEach(e => {
if (getComputedStyle(e).display === 'none') { e.dataset.slide = 'down'; e.style.display = 'block'; }
else { e.dataset.slide = 'up'; e.style.display = 'none'; }
});
return this;
};
const queues = new WeakMap();
JQ.prototype.animate = function(props, cb) {
this.els.forEach(e => {
if (!queues.has(e)) queues.set(e, []);
queues.get(e).push({ props, cb });
const step = queues.get(e)[0];
if (!e.dataset.animating) {
this._runStep(e);
}
});
return this;
};
JQ.prototype._runStep = function(e) {
const q = queues.get(e) || [];
if (!q.length) { delete e.dataset.animating; return; }
e.dataset.animating = '1';
const cur = q[0];
Object.entries(cur.props).forEach(([k, v]) => {
if (v === 'toggle') {
e.style.display = getComputedStyle(e).display === 'none' ? 'block' : 'none';
} else if (typeof v === 'string' && v.startsWith('+=')) {
const delta = parseFloat(v.slice(2));
const base = parseFloat(getComputedStyle(e)[k]) || 0;
e.style[k] = (base + delta) + 'px';
} else {
e.style[k] = String(v);
}
});
q.shift();
if (typeof cur.cb === 'function') cur.cb.call(e);
if (q.length) this._runStep(e);
else delete e.dataset.animating;
};
JQ.prototype.stop = function(clearQueue, jumpToEnd) {
this.els.forEach(e => {
if (clearQueue) queues.set(e, []);
if (jumpToEnd) e.dataset.jumped = '1';
delete e.dataset.animating;
});
return this;
};
['click', 'dblclick', 'mouseenter', 'mouseleave', 'mousedown', 'mouseup', 'focus', 'blur'].forEach(ev => {
JQ.prototype[ev] = function(fn) {
if (!fn) { this.els.forEach(e => e.dispatchEvent(new Event(ev, { bubbles: true }))); return this; }
this.els.forEach(e => e.addEventListener(ev, fn));
return this;
};
});
JQ.prototype.hover = function(fnIn, fnOut) { return this.mouseenter(fnIn).mouseleave(fnOut); };
JQ.prototype.text = function(val) {
if (val === undefined) return this.els[0] ? this.els[0].textContent : '';
this.els.forEach((e, i) => { e.textContent = typeof val === 'function' ? val(i, e.textContent) : val; });
return this;
};
JQ.prototype.html = function(val) {
if (val === undefined) return this.els[0] ? this.els[0].innerHTML : '';
this.els.forEach((e, i) => { e.innerHTML = typeof val === 'function' ? val(i, e.innerHTML) : val; });
return this;
};
JQ.prototype.val = function(val) {
if (val === undefined) return this.els[0] ? this.els[0].value : '';
this.els.forEach(e => { e.value = val; });
return this;
};
JQ.prototype.attr = function(k, v) {
if (typeof k === 'object') {
Object.entries(k).forEach(([ak, av]) => this.attr(ak, av));
return this;
}
if (v === undefined) return this.els[0] ? this.els[0].getAttribute(k) : null;
this.els.forEach((e, i) => {
const nv = typeof v === 'function' ? v(i, e.getAttribute(k)) : v;
e.setAttribute(k, nv);
});
return this;
};
function toNodes(arg) {
if (arg instanceof JQ) return arg.els;
if (arg instanceof Node) return [arg];
const tpl = document.createElement('template');
tpl.innerHTML = String(arg);
return Array.from(tpl.content.childNodes);
}
JQ.prototype.append = function(...args) {
this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.appendChild(n))));
return this;
};
JQ.prototype.prepend = function(...args) {
this.els.forEach(e => args.reverse().forEach(a => toNodes(a).reverse().forEach(n => e.insertBefore(n, e.firstChild))));
return this;
};
JQ.prototype.after = function(...args) {
this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.parentNode.insertBefore(n, e.nextSibling))));
return this;
};
JQ.prototype.before = function(...args) {
this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.parentNode.insertBefore(n, e))));
return this;
};
JQ.prototype.remove = function(filter) {
this.els.forEach(e => { if (!filter || e.matches(filter)) e.remove(); });
return this;
};
JQ.prototype.empty = function() { this.els.forEach(e => { e.innerHTML = ''; }); return this; };
JQ.prototype.addClass = function(c) {
const cls = c.trim().split(/\s+/);
this.els.forEach(e => e.classList.add(...cls));
return this;
};
JQ.prototype.removeClass = function(c) {
const cls = c.trim().split(/\s+/);
this.els.forEach(e => e.classList.remove(...cls));
return this;
};
JQ.prototype.toggleClass = function(c) {
this.els.forEach(e => e.classList.toggle(c));
return this;
};
JQ.prototype.css = function(k, v) {
if (typeof k === 'object') {
Object.entries(k).forEach(([ck, cv]) => this.css(ck, cv));
return this;
}
if (v === undefined) return this.els[0] ? getComputedStyle(this.els[0])[k] : '';
this.els.forEach(e => { e.style[k] = v; });
return this;
};
JQ.prototype.width = function(v) {
const e = this.els[0];
if (v !== undefined) { this.els.forEach(el => { el.style.width = v + 'px'; }); return this; }
if (e === window) return window.innerWidth;
if (e === document) return document.documentElement.scrollWidth;
const cs = getComputedStyle(e);
return parseFloat(cs.width);
};
JQ.prototype.height = function(v) {
const e = this.els[0];
if (v !== undefined) { this.els.forEach(el => { el.style.height = v + 'px'; }); return this; }
if (e === window) return window.innerHeight;
if (e === document) return document.documentElement.scrollHeight;
const cs = getComputedStyle(e);
return parseFloat(cs.height);
};
JQ.prototype.innerWidth = function() {
const e = this.els[0];
const cs = getComputedStyle(e);
return parseFloat(cs.width) + parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
};
JQ.prototype.innerHeight = function() {
const e = this.els[0];
const cs = getComputedStyle(e);
return parseFloat(cs.height) + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
};
JQ.prototype.outerWidth = function(incMargin) {
const e = this.els[0];
const cs = getComputedStyle(e);
return e.offsetWidth + (incMargin ? parseFloat(cs.marginLeft) + parseFloat(cs.marginRight) : 0);
};
JQ.prototype.outerHeight = function(incMargin) {
const e = this.els[0];
const cs = getComputedStyle(e);
return e.offsetHeight + (incMargin ? parseFloat(cs.marginTop) + parseFloat(cs.marginBottom) : 0);
};
JQ.prototype.parent = function() { return new JQ(this.els[0] ? [this.els[0].parentElement] : []); };
JQ.prototype.parents = function() {
const out = [];
let p = this.els[0] && this.els[0].parentElement;
while (p) { out.push(p); p = p.parentElement; }
return new JQ(out);
};
JQ.prototype.parentsUntil = function(sel) {
const out = [];
let p = this.els[0] && this.els[0].parentElement;
while (p && !p.matches(sel)) { out.push(p); p = p.parentElement; }
return new JQ(out);
};
JQ.prototype.children = function() { return new JQ(this.els[0] ? Array.from(this.els[0].children) : []); };
JQ.prototype.find = function(sel) { return new JQ(this.els[0] ? Array.from(this.els[0].querySelectorAll(sel)) : []); };
JQ.prototype.siblings = function() {
const e = this.els[0];
return new JQ(e ? Array.from(e.parentElement.children).filter(n => n !== e) : []);
};
JQ.prototype.next = function() { return new JQ(this.els[0] && this.els[0].nextElementSibling ? [this.els[0].nextElementSibling] : []); };
JQ.prototype.nextAll = function() {
const out = [];
let n = this.els[0] && this.els[0].nextElementSibling;
while (n) { out.push(n); n = n.nextElementSibling; }
return new JQ(out);
};
JQ.prototype.nextUntil = function(sel) {
const out = [];
let n = this.els[0] && this.els[0].nextElementSibling;
while (n && !n.matches(sel)) { out.push(n); n = n.nextElementSibling; }
return new JQ(out);
};
JQ.prototype.load = async function(urlExpr, cb) {
const [url, frag] = urlExpr.split(/\s+/);
const res = await fetch(url);
const txt = await res.text();
if (frag) {
const tpl = document.createElement('template');
tpl.innerHTML = txt;
const found = tpl.content.querySelector(frag);
this.els.forEach(e => { e.innerHTML = found ? found.outerHTML : ''; });
} else {
this.els.forEach(e => { e.innerHTML = txt; });
}
if (cb) cb(txt, res.ok ? 'success' : 'error');
return this;
};
$.get = async function(url) {
const res = await fetch(url);
return await res.json();
};
$.post = async function(url, data) {
const res = await fetch(url, { method: 'POST', body: new URLSearchParams(data).toString() });
return await res.json();
};
window.$ = $;
</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():
socketserver.TCPServer.allow_reuse_address = True
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LoopbackHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page(viewport={"width": 800, "height": 600})
page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
# Case 1: Selectors, events, hide/show/toggle
res1 = page.evaluate("""() => {
const log = [];
$('#btn-self').click(function() { $(this).hide(); log.push('click'); });
$('#ev-btn')
.dblclick(() => log.push('dblclick'))
.hover(() => log.push('enter'), () => log.push('leave'))
.mousedown(() => log.push('down'))
.mouseup(() => log.push('up'));
$('#ev-input').focus(() => log.push('focus')).blur(() => log.push('blur'));
$('#btn-self').click();
const selfHidden = $('#btn-self').css('display') === 'none';
$('.test').hide();
const classHidden = $('.test').css('display') === 'none';
$('#test').hide();
const idHidden = $('#test').css('display') === 'none';
$('p.p-item').hide();
const pHiddenCount = $('p.p-item').els.filter(e => getComputedStyle(e).display === 'none').length;
$('#ev-btn').dblclick().mouseenter().mouseleave().mousedown().mouseup();
$('#ev-input').focus().blur();
$('#test').show();
const shownAfterShow = $('#test').css('display') === 'block';
$('#test').toggle();
const hiddenAfterToggle = $('#test').css('display') === 'none';
return { selfHidden, classHidden, idHidden, pHiddenCount, shownAfterShow, hiddenAfterToggle, log };
}""")
exp1 = {
"selfHidden": True,
"classHidden": True,
"idHidden": True,
"pHiddenCount": 2,
"shownAfterShow": True,
"hiddenAfterToggle": True,
"log": ["click", "dblclick", "enter", "leave", "down", "up", "focus", "blur"],
}
cases.append(dict(
name="selectors_events_visibility",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Fade, slide, animate (multi-css, relative, toggle, callback), stop
res2 = page.evaluate("""() => {
const steps = [];
$('#fx-box').fadeOut();
const afterFadeOut = $('#fx-box').css('display');
$('#fx-box').fadeIn();
const afterFadeIn = $('#fx-box').css('opacity');
$('#fx-box').fadeTo(0.4);
const afterFadeTo = $('#fx-box').css('opacity');
$('#fx-box').fadeToggle();
const afterFadeToggle = $('#fx-box').css('display');
$('#fx-box').slideDown();
const afterSlideDown = $('#fx-box').css('display');
$('#fx-box').slideUp();
const afterSlideUp = $('#fx-box').css('display');
$('#fx-box').slideToggle();
const afterSlideToggle = $('#fx-box').css('display');
$('#anim-box')
.animate({ left: '+=50px', opacity: '0.5', width: '+=30px' }, () => steps.push('cb1'))
.animate({ height: 'toggle' }, () => steps.push('cb2'));
const animState = {
left: $('#anim-box').css('left'),
width: $('#anim-box').css('width'),
opacity: $('#anim-box').css('opacity'),
display: $('#anim-box').css('display'),
};
$('#anim-box').stop(true, true);
const stoppedJump = document.getElementById('anim-box').dataset.jumped === '1';
return { afterFadeOut, afterFadeIn, afterFadeTo, afterFadeToggle, afterSlideDown, afterSlideUp, afterSlideToggle, animState, steps, stoppedJump };
}""")
exp2 = {
"afterFadeOut": "none",
"afterFadeIn": "1",
"afterFadeTo": "0.4",
"afterFadeToggle": "none",
"afterSlideDown": "block",
"afterSlideUp": "none",
"afterSlideToggle": "block",
"animState": {"left": "50px", "width": "80px", "opacity": "0.5", "display": "none"},
"steps": ["cb1", "cb2"],
"stoppedJump": True,
}
cases.append(dict(
name="effects_fade_slide_animate_stop",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: DOM get/set/insert/remove, classes, css(), dimensions
res3 = page.evaluate("""() => {
const origText = $('#dom-p').text();
const origHtml = $('#dom-p').html();
const origVal = $('#dom-in').val();
const origHref = $('#dom-link').attr('href');
$('#dom-p').text((i, old) => old + '!');
const newText = $('#dom-p').text();
$('#dom-in').val('bob');
$('#dom-link').attr({ href: 'https://example.org/jq', title: 'updated' });
$('#dom-link').attr('href', (i, old) => old + '/v2');
$('#dom-list').append('<li>End</li>', document.createElement('li'));
$('#dom-list').prepend('<li>Start</li>');
$('#dom-p').before('<span class="ins">Before</span>').after('<span class="ins">After</span>');
$('#dom-list li').remove('.del');
const countAfterFilterRemove = $('#dom-list li').length;
$('#dom-list').empty();
const countAfterEmpty = $('#dom-list li').length;
$('#dom-cls').addClass('blue important').removeClass('blue').toggleClass('active');
const clsList = Array.from(document.getElementById('dom-cls').classList).sort();
const origBg = $('#dim-box').css('backgroundColor');
$('#dim-box').css({ backgroundColor: 'rgb(0, 128, 0)', fontSize: '14px' });
const newBg = $('#dim-box').css('backgroundColor');
const dims = {
w: $('#dim-box').width(),
h: $('#dim-box').height(),
iw: $('#dim-box').innerWidth(),
ih: $('#dim-box').innerHeight(),
ow: $('#dim-box').outerWidth(),
oh: $('#dim-box').outerHeight(),
owm: $('#dim-box').outerWidth(true),
ohm: $('#dim-box').outerHeight(true),
winW: $(window).width(),
winH: $(window).height(),
};
$('#dim-box').width(200).height(90);
const resized = [$('#dim-box').width(), $('#dim-box').height()];
return {
origText, origHtml, origVal, origHref, newText,
newVal: $('#dom-in').val(),
newHref: $('#dom-link').attr('href'),
newTitle: $('#dom-link').attr('title'),
countAfterFilterRemove, countAfterEmpty, clsList,
origBg, newBg, dims, resized,
};
}""")
exp3 = {
"origText": "Hello World",
"origHtml": "Hello <b>World</b>",
"origVal": "alice",
"origHref": "https://example.org",
"newText": "Hello World!",
"newVal": "bob",
"newHref": "https://example.org/jq/v2",
"newTitle": "updated",
"countAfterFilterRemove": 4,
"countAfterEmpty": 0,
"clsList": ["active", "important"],
"origBg": "rgb(255, 0, 0)",
"newBg": "rgb(0, 128, 0)",
"dims": {
"w": 120, "h": 60, "iw": 140, "ih": 80,
"ow": 144, "oh": 84, "owm": 154, "ohm": 94,
"winW": 800, "winH": 600,
},
"resized": [200, 90],
}
cases.append(dict(
name="dom_html_attr_css_dimensions",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
# Case 4: Traversal (ancestors/descendants/siblings) + local loopback AJAX + canvas particles
res4 = page.evaluate("""async () => {
const parentId = $('#target-span').parent().els[0].id;
const untilIds = $('#target-span').parentsUntil('#sec-trav').els.map(e => e.id);
const childIds = $('#parent').children().els.map(e => e.id);
const foundSpans = $('#grandparent').find('span').els.map(e => e.id);
const sibIds = $('#target-span').siblings().els.map(e => e.id);
const nextId = $('#target-span').next().els[0].id;
const nextAllIds = $('#target-span').nextAll().els.map(e => e.id);
const nextUntilIds = $('#target-span').nextUntil('#sib-e').els.map(e => e.id);
let loadCbStatus = '';
await $('#load-whole').load('/snippet.html', (txt, status) => { loadCbStatus = status; });
await $('#load-part').load('/snippet.html #part');
const getRes = await $.get('/api/get');
const postRes = await $.post('/api/post', { name: 'jquery', topic: 'ajax' });
// Canvas particle step verification
const cvs = document.getElementById('particles');
const ctx = cvs.getContext('2d');
const pts = [{ x: 10, y: 10, vx: 3, vy: 2 }, { x: 40, y: 20, vx: -2, vy: 1 }];
ctx.clearRect(0, 0, cvs.width, cvs.height);
pts.forEach(pt => {
pt.x += pt.vx; pt.y += pt.vy;
ctx.fillStyle = '#09f';
ctx.fillRect(pt.x, pt.y, 4, 4);
});
const px = Array.from(ctx.getImageData(13, 12, 1, 1).data);
return {
parentId, untilIds, childIds, foundSpans, sibIds, nextId, nextAllIds, nextUntilIds,
loadWholeText: $('#load-whole').text(),
loadPartText: $('#load-part').text(),
loadCbStatus, getRes, postRes,
particleMoved: [pts[0].x, pts[0].y],
particlePixelAlpha: px[3],
};
}""")
exp4 = {
"parentId": "parent",
"untilIds": ["parent", "grandparent"],
"childIds": ["sib-a", "target-span", "sib-c", "sib-d", "sib-e"],
"foundSpans": ["sib-a", "target-span", "sib-c"],
"sibIds": ["sib-a", "sib-c", "sib-d", "sib-e"],
"nextId": "sib-c",
"nextAllIds": ["sib-c", "sib-d", "sib-e"],
"nextUntilIds": ["sib-c", "sib-d"],
"loadWholeText": "Local AJAX FragmentExtra",
"loadPartText": "Local AJAX Fragment",
"loadCbStatus": "success",
"getRes": {"method": "GET", "status": "ok", "msg": "hello-get"},
"postRes": {"method": "POST", "received": "name=jquery&topic=ajax"},
"particleMoved": [13, 12],
"particlePixelAlpha": 255,
}
cases.append(dict(
name="traversal_and_local_ajax",
expected=exp4,
actual=res4,
passed=(res4 == exp4),
))
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 在离线 Chromium 中通过 4 组综合用例:全部选择器与 8 类事件日志一致,动画与 stop() 终态精确,盒模型 width/innerWidth/outerWidth/outerWidth(true) 分别为 120/140/144/154,本地回环 load()/$.get()/$.post() 及 Canvas 粒子帧绘制全部通过。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:6ccc84436cad6324ed752173b691686cd14865d24ab01e777a36d213257764ed
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:f07d971c42aa648ac81fdba78c6a9bc35aefe07f263c2162bf85adfe0d1907fa
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
outerWidth() 与 outerWidth(true) 的统计边界有什么区别?load('/snippet.html #part') 与直接 load('/snippet.html') 有何不同?
展开参考解答
outerWidth() 包含内容宽度、左右 padding 与左右 border;传入 true 后还会把左右 margin 计入总宽度。load() 附加 CSS 选择器后,会在解析返回 HTML 片段时仅抽取匹配 #part 的子元素插入目标容器,而不是整段替换。