jQuery 停止动画
核对 jQuery stop(stopAll, goToEnd) 中断滑动、淡入淡出与自定义动画队列的四种参数组合及离线 Chromium 实测行为。
学完这一章,你能够
- 核对 jQuery stop(stopAll, goToEnd) 中断滑动、淡入淡出与自定义动画队列的四种参数组合及离线 Chromium 实测行为。
stop() 的用途与滑动面板中断演示
在页面交互中,用户可能在面板展开、淡入淡出或位移动画尚未结束时就触发新操作。jQuery 的 `stop()` 方法专门用于在动画或效果完成之前将其立即中断。以典型的滑动面板交互为例:点击触发栏向下或向上缓慢滑动面板(如设置较长过渡时长),面板内部承载说明文案;在滑动途中点击“停止滑动”按钮调用 `.stop()`,面板就会停在当前的中间高度位置,避免动画继续失控执行。
围绕上述机制,常见演示分为两类:一是不带参数的默认滑动中断(点击后仅中止当前正在进行的滑动过程),二是显式传入控制参数的带参动画中断(验证多步动画队列的清理方式与终点跳转行为)。
stop(stopAll, goToEnd) 语法与队列控制语义
`stop()` 适用于全部 jQuery 效果方法,包括滑动(`slideDown`/`slideUp`/`slideToggle`)、淡入淡出(`fadeIn`/`fadeOut`/`fadeTo`)以及 `animate()` 自定义属性动画。标准调用语法为 `$(selector).stop(stopAll, goToEnd);`,两个布尔参数均可选。
第一个参数 `stopAll` 决定是否清空该元素尚未开始的后续动画队列,默认值为 `false`——即仅停止当前正在运行的活动动画,排在队列中的后续动画会立即顺延启动;若设为 `true`,则会同时清空剩余队列。第二个参数 `goToEnd` 决定是否把当前被中断的动画立刻推进到目标终点状态,默认值为 `false`(停留在中断瞬间的当前帧)。因此不带参数调用 `.stop()` 等价于 `.stop(false, false)`,只停止当前活动动画并保持当前进度。
在基本中断写法 `$('#stop').click(function(){ $('#panel').stop(); });` 的基础上,本站离线 Chromium 实验完整测量了全部四种参数组合:对目标高度 `100px`、耗时 `1000ms` 的面板滑动在 `500ms` 处调用默认 `.stop()`,面板高度定格在 `50px`(`display: block`)且不再变化;对串联了 `left: 200px` 与 `top: 120px` 两段动画的方块在首段过半(`left: 100px`)时分别调用 `.stop(false, false)` 后队列继续执行至 `left: 100px, top: 120px`,调用 `.stop(true, false)` 后队列清空并停留在 `left: 100px, top: 0px`,调用 `.stop(true, true)` 后当前动画直接跳至 `left: 200px` 且队列清空(`top: 0px`),而对 `fadeTo(1000, 0.2)` 与 `animate({height: '160px'}, 1000)` 调用 `.stop(false, true)` 后首段立即完成至 `opacity: 0.2` 且第二段继续跑完至 `height: 160px`。
离线 Chromium 实测 stop() 四种参数组合与动画队列中断
"""Offline Playwright Chromium lab for jQuery Chapter 11 (stop)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
body { margin: 0; font-family: sans-serif; }
#stop-btn { margin-left: 25px; }
.flip, #panel {
width: 300px;
padding: 5px;
text-align: center;
background: #e5eecc;
border: 1px solid #c3c3c3;
}
#panel {
height: 100px;
display: none;
overflow: hidden;
}
#box {
position: relative;
left: 0px;
top: 0px;
width: 100px;
height: 100px;
opacity: 1;
background: #98bf21;
}
</style>
</head>
<body>
<button id="stop-btn" type="button">停止滑动</button>
<p class="flip">点击这里,向上/向下滑动面板</p>
<div id="panel">面板内容区域</div>
<div id="box">动画方块</div>
<script>
(function () {
const queues = new WeakMap();
const activeTimers = new Set();
function getQueue(el) {
if (!queues.has(el)) queues.set(el, { active: null, pending: [] });
return queues.get(el);
}
function readNumericProp(el, prop) {
const cs = getComputedStyle(el);
if (prop === 'opacity') return parseFloat(cs.opacity) || 0;
const val = parseFloat(cs[prop]);
return Number.isNaN(val) ? 0 : val;
}
function writeProp(el, prop, value) {
if (prop === 'opacity') {
el.style.opacity = String(Number(value.toFixed(4)));
} else {
el.style[prop] = Number(value.toFixed(2)) + 'px';
}
}
function startNext(el) {
const q = getQueue(el);
if (q.active || q.pending.length === 0) return;
const job = q.pending.shift();
if (job.onStart) job.onStart();
const startVals = {};
for (const k of Object.keys(job.targets)) {
startVals[k] = readNumericProp(el, k);
}
q.active = {
el,
duration: job.duration,
elapsed: 0,
startVals,
targets: job.targets,
onDone: job.onDone,
};
activeTimers.add(q.active);
}
function applyProgress(anim, ratio) {
const clamped = Math.max(0, Math.min(1, ratio));
for (const [k, endVal] of Object.entries(anim.targets)) {
const cur = anim.startVals[k] + (endVal - anim.startVals[k]) * clamped;
writeProp(anim.el, k, cur);
}
}
window.__advance = function (ms) {
const snapshot = Array.from(activeTimers);
for (const anim of snapshot) {
if (!activeTimers.has(anim)) continue;
anim.elapsed += ms;
if (anim.elapsed >= anim.duration) {
applyProgress(anim, 1);
activeTimers.delete(anim);
const q = getQueue(anim.el);
if (q.active === anim) q.active = null;
if (anim.onDone) anim.onDone();
startNext(anim.el);
} else {
applyProgress(anim, anim.elapsed / anim.duration);
}
}
};
function JQ(els) {
this.els = Array.from(els);
this.length = this.els.length;
}
JQ.prototype.click = function (fn) {
this.els.forEach((el) => el.addEventListener('click', fn));
return this;
};
JQ.prototype.slideToggle = function (duration) {
const dur = typeof duration === 'number' ? duration : 400;
this.els.forEach((el) => {
const q = getQueue(el);
const isHidden = getComputedStyle(el).display === 'none';
if (isHidden) {
q.pending.push({
duration: dur,
targets: { height: 100 },
onStart: () => {
el.style.display = 'block';
el.style.height = '0px';
},
});
} else {
q.pending.push({
duration: dur,
targets: { height: 0 },
onDone: () => {
el.style.display = 'none';
},
});
}
startNext(el);
});
return this;
};
JQ.prototype.fadeTo = function (duration, opacity) {
const dur = typeof duration === 'number' ? duration : 400;
this.els.forEach((el) => {
const q = getQueue(el);
q.pending.push({ duration: dur, targets: { opacity } });
startNext(el);
});
return this;
};
JQ.prototype.animate = function (props, duration) {
const dur = typeof duration === 'number' ? duration : 400;
const targets = {};
for (const [k, v] of Object.entries(props)) {
targets[k] = typeof v === 'string' ? parseFloat(v) : v;
}
this.els.forEach((el) => {
const q = getQueue(el);
q.pending.push({ duration: dur, targets });
startNext(el);
});
return this;
};
JQ.prototype.stop = function (stopAll, goToEnd) {
const clearQueue = Boolean(stopAll);
const jumpEnd = Boolean(goToEnd);
this.els.forEach((el) => {
const q = getQueue(el);
const cur = q.active;
if (clearQueue) {
q.pending.length = 0;
}
if (cur) {
activeTimers.delete(cur);
q.active = null;
if (jumpEnd) {
applyProgress(cur, 1);
if (cur.onDone) cur.onDone();
}
}
if (!clearQueue) {
startNext(el);
}
});
return this;
};
window.$ = function (sel) {
return new JQ(document.querySelectorAll(sel));
};
window.__queueInfo = function (sel) {
const el = document.querySelector(sel);
const q = getQueue(el);
return { active: Boolean(q.active), pending: q.pending.length };
};
window.__resetBox = function () {
const el = document.querySelector('#box');
const q = getQueue(el);
if (q.active) activeTimers.delete(q.active);
q.active = null;
q.pending.length = 0;
el.style.left = '0px';
el.style.top = '0px';
el.style.height = '100px';
el.style.opacity = '1';
};
$('.flip').click(function () {
$('#panel').slideToggle(1000);
});
$('#stop-btn').click(function () {
$('#panel').stop();
});
})();
</script>
</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 p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1000, "height": 700})
page.set_content(HTML_DOC, wait_until="load")
# Case 1: default stop() halts slideToggle mid-way
page.click(".flip")
page.evaluate("window.__advance(500)")
mid_height = page.evaluate("getComputedStyle(document.querySelector('#panel')).height")
page.click("#stop-btn")
page.evaluate("window.__advance(600)")
c1 = page.evaluate("""() => {
const cs = getComputedStyle(document.querySelector('#panel'));
const q = window.__queueInfo('#panel');
return { display: cs.display, height: cs.height, active: q.active, pending: q.pending };
}""")
c1["mid_height"] = mid_height
exp1 = {"mid_height": "50px", "display": "block", "height": "50px", "active": False, "pending": 0}
cases.append(dict(name="stop_default_slide_panel", expected=exp1, actual=c1, passed=c1 == exp1))
# Case 2: stop(false, false) halts current animation, runs queued next animation
c2 = page.evaluate("""() => {
window.__resetBox();
$('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
window.__advance(500);
const midLeft = getComputedStyle(document.querySelector('#box')).left;
$('#box').stop(false, false);
const afterStopQ = window.__queueInfo('#box');
window.__advance(1000);
const cs = getComputedStyle(document.querySelector('#box'));
return { midLeft, left: cs.left, top: cs.top, nextStarted: afterStopQ.active };
}""")
exp2 = {"midLeft": "100px", "left": "100px", "top": "120px", "nextStarted": True}
cases.append(dict(name="stop_false_false_continues_queue", expected=exp2, actual=c2, passed=c2 == exp2))
# Case 3: stop(true, false) halts current animation AND clears queue
c3 = page.evaluate("""() => {
window.__resetBox();
$('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
window.__advance(500);
$('#box').stop(true, false);
const afterStopQ = window.__queueInfo('#box');
window.__advance(1000);
const cs = getComputedStyle(document.querySelector('#box'));
return { left: cs.left, top: cs.top, active: afterStopQ.active, pending: afterStopQ.pending };
}""")
exp3 = {"left": "100px", "top": "0px", "active": False, "pending": 0}
cases.append(dict(name="stop_true_false_clears_queue", expected=exp3, actual=c3, passed=c3 == exp3))
# Case 4: stop(true, true) vs stop(false, true) with fadeTo & animate
c4 = page.evaluate("""() => {
window.__resetBox();
$('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
window.__advance(500);
$('#box').stop(true, true);
window.__advance(1000);
const cs1 = getComputedStyle(document.querySelector('#box'));
const tt = { left: cs1.left, top: cs1.top };
window.__resetBox();
$('#box').fadeTo(1000, 0.2).animate({ height: '160px' }, 1000);
window.__advance(500);
$('#box').stop(false, true);
window.__advance(1000);
const cs2 = getComputedStyle(document.querySelector('#box'));
const ft = { opacity: cs2.opacity, height: cs2.height };
return { true_true: tt, false_true: ft };
}""")
exp4 = {
"true_true": {"left": "200px", "top": "0px"},
"false_true": {"opacity": "0.2", "height": "160px"},
}
cases.append(dict(name="stop_gotoend_and_fade_queue", expected=exp4, actual=c4, passed=c4 == exp4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对默认 stop() 将 100px 滑动面板停在 50px,stop(false,false) 停在 left=100px 并续跑 top=120px,stop(true,false) 清空队列停在 top=0px,stop(true,true) 跳至 left=200px 且 stop(false,true) 跳至 opacity=0.2 并续跑 height=160px。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:52be0cb21851370e1220c2d85beebffff9cc7669af7a8a95dd428e6816756c98
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:baafe1ad80e56897b66e30db838160271f2df1d20b8091ac19342d13b77b210d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在多步串联动画中,调用 `.stop()`、`.stop(true)` 与 `.stop(true, true)` 分别会产生什么不同结果?
展开参考解答
`.stop()` 等价于 `.stop(false, false)`,仅停住当前动画于当前帧并立即执行下一段排队动画;`.stop(true)` 清空全部后续队列并停在当前帧;`.stop(true, true)` 清空后续队列且将当前动画瞬间推进至其目标终点状态。