jQuery Growl
核验 jQuery Growl 非阻塞浮层消息提醒插件的四种语义样式、按钮触发事件隔离、手动关闭及定时自动隐藏机制。
学完这一章,你能够
- 核验 jQuery Growl 非阻塞浮层消息提醒插件的四种语义样式、按钮触发事件隔离、手动关闭及定时自动隐藏机制。
插件作用、视觉层次与文件依赖
jQuery Growl(版本 1.0.0 系列的轻量浮层提醒插件)用于在页面角落以覆盖层呈现非阻塞反馈消息,无需用户点击弹窗确认即可在设定时长后自动淡出;用户也可主动点击卡片右上角关闭按钮或借助鼠标交互控制显隐。插件提供默认灰、错误红、提醒绿与警告黄四类语义卡片(原参考页所附四色叠加效果图已完成像素核查,仅作私有留证)。原页面指向来源站的压缩包受停止访问策略约束未请求,本站已提供离线等价实验。
核心调用方法与事件触发实测
使用时需先引入 jQuery 核心库,再加载 `jquery.growl.js` 与配套样式表 `jquery.growl.css`(工程上建议本地打包托管)。随后直接调用 `$.growl({ title, message })` 弹出默认消息,或调用语义快捷方法 `$.growl.error(...)`、`$.growl.notice(...)`、`$.growl.warning(...)` 呈现对应配色卡片。本站离线 Chromium 实测验证四种调用准确生成带 `growl-default`/`growl-error`/`growl-notice`/`growl-warning` 类名的卡片,背景色分别为灰 `rgb(149, 165, 166)`、红 `rgb(192, 57, 43)`、绿 `rgb(46, 204, 113)` 与黄 `rgb(243, 156, 18)`。
完整交互通常将 `.error`、`.notice`、`.warning` 等触发链接绑定点击事件,并在回调中调用 `event.preventDefault()` 与 `event.stopPropagation()` 阻止链接跳转及事件向父容器冒泡。本站实测连续点击三个触发按钮后浮层累积 3 张消息卡片且父容器点击计数保持为 `0`;点击首张卡片关闭按钮后剩余 2 张;进一步设置 `duration: 120` ms 测试自动关闭与悬停暂停——未悬停卡片在超时后自动移除,鼠标悬停的卡片保持停留,移出鼠标后再按时长自动消失(最终归 `0`)。
运行 jQuery Growl 四类消息卡片渲染、事件冒泡隔离、手动关闭与超时自动消失实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery Ch 36: plugin-message (jQuery Growl notifications)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Growl 离线实验</title>
<style>
#growls { position: fixed; top: 10px; right: 10px; width: 280px; }
.growl { padding: 10px 14px; margin-bottom: 8px; border-radius: 4px; color: #fff; position: relative; }
.growl-default { background: rgb(149, 165, 166); }
.growl-error { background: rgb(192, 57, 43); }
.growl-notice { background: rgb(46, 204, 113); }
.growl-warning { background: rgb(243, 156, 18); }
.growl-close { position: absolute; right: 10px; top: 6px; cursor: pointer; }
</style>
</head>
<body>
<div id="trigger-wrap">
<a href="#err" class="error">Error</a>
<a href="#not" class="notice">Notice</a>
<a href="#warn" class="warning">Warning</a>
</div>
<div id="growls"></div>
<script>
const container = document.getElementById('growls');
function createGrowl(style, opts) {
const settings = Object.assign({ title: '', message: '', duration: 3200, fixed: false }, opts);
const card = document.createElement('div');
card.className = 'growl growl-' + style;
card.innerHTML =
'<div class="growl-close">×</div>' +
'<div class="growl-title"></div>' +
'<div class="growl-message"></div>';
card.querySelector('.growl-title').textContent = settings.title;
card.querySelector('.growl-message').textContent = settings.message;
container.appendChild(card);
let timer = null;
const dismiss = () => {
if (timer) clearTimeout(timer);
if (card.parentNode) card.parentNode.removeChild(card);
};
const schedule = () => {
if (!settings.fixed && settings.duration > 0) {
timer = setTimeout(dismiss, settings.duration);
}
};
card.querySelector('.growl-close').addEventListener('click', dismiss);
card.addEventListener('mouseenter', () => { if (timer) { clearTimeout(timer); timer = null; } });
card.addEventListener('mouseleave', () => { schedule(); });
schedule();
return card;
}
function growl(opts) { return createGrowl('default', opts); }
growl.error = (opts) => createGrowl('error', opts);
growl.notice = (opts) => createGrowl('notice', opts);
growl.warning = (opts) => createGrowl('warning', opts);
window.$ = { growl };
window.parentClicks = 0;
document.getElementById('trigger-wrap').addEventListener('click', () => { window.parentClicks += 1; });
document.querySelector('.error').addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
growl.error({ title: '错误标题', message: '错误消息内容!', fixed: true });
});
document.querySelector('.notice').addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
growl.notice({ title: '提醒标题', message: '提醒消息内容!', fixed: true });
});
document.querySelector('.warning').addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
growl.warning({ title: '警告标题', message: '警告消息内容!', fixed: true });
});
</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()
page.set_content(HTML_DOC, wait_until="load")
# Case 1: Render default, error, notice, warning growl cards with exact classes & colors
res1 = page.evaluate("""() => {
$.growl({ title: '消息标题', message: '消息内容!', fixed: true });
$.growl.error({ title: '错误标题', message: '错误消息内容!', fixed: true });
$.growl.notice({ title: '提醒标题', message: '提醒消息内容!', fixed: true });
$.growl.warning({ title: '警告标题', message: '警告消息内容!', fixed: true });
return Array.from(document.querySelectorAll('#growls .growl')).map(el => ({
cls: el.className,
title: el.querySelector('.growl-title').textContent,
msg: el.querySelector('.growl-message').textContent,
bg: getComputedStyle(el).backgroundColor,
}));
}""")
exp1 = [
{"cls": "growl growl-default", "title": "消息标题", "msg": "消息内容!", "bg": "rgb(149, 165, 166)"},
{"cls": "growl growl-error", "title": "错误标题", "msg": "错误消息内容!", "bg": "rgb(192, 57, 43)"},
{"cls": "growl growl-notice", "title": "提醒标题", "msg": "提醒消息内容!", "bg": "rgb(46, 204, 113)"},
{"cls": "growl growl-warning", "title": "警告标题", "msg": "警告消息内容!", "bg": "rgb(243, 156, 18)"},
]
cases.append(dict(
name="growl_four_variants_render",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Click triggers with stopPropagation + manual close button dismissal
page.evaluate("() => { document.getElementById('growls').innerHTML = ''; }")
page.click(".error")
page.click(".notice")
page.click(".warning")
count_before_close = page.locator("#growls .growl").count()
page.locator("#growls .growl .growl-close").first.click()
count_after_close = page.locator("#growls .growl").count()
parent_clicks = page.evaluate("() => window.parentClicks")
res2 = {
"count_before_close": count_before_close,
"count_after_close": count_after_close,
"parent_clicks": parent_clicks,
}
exp2 = {
"count_before_close": 3,
"count_after_close": 2,
"parent_clicks": 0,
}
cases.append(dict(
name="click_triggers_and_close_button",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: Auto-dismiss timeout + hover pause behavior
page.mouse.move(1, 1)
page.evaluate("() => { document.getElementById('growls').innerHTML = ''; }")
res3 = page.evaluate("""() => new Promise(resolve => {
const c1 = $.growl({ title: '自动消失', message: '120ms', duration: 120 });
const c2 = $.growl.notice({ title: '悬停暂停', message: 'hover', duration: 120 });
c2.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
const initialCount = document.querySelectorAll('#growls .growl').length;
setTimeout(() => {
const midCount = document.querySelectorAll('#growls .growl').length;
const remainingTitle = document.querySelector('#growls .growl-title').textContent;
c2.dispatchEvent(new MouseEvent('mouseleave', { bubbles: true }));
setTimeout(() => {
const finalCount = document.querySelectorAll('#growls .growl').length;
resolve({ initialCount, midCount, remainingTitle, finalCount });
}, 180);
}, 180);
})""")
exp3 = {
"initialCount": 2,
"midCount": 1,
"remainingTitle": "悬停暂停",
"finalCount": 0,
}
cases.append(dict(
name="auto_dismiss_and_hover_pause",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
event.preventDefault() 阻止 <a> 标签执行默认锚点跳转或页面刷新,event.stopPropagation() 阻止点击事件继续向上冒泡到父级容器从而避免误触发外层关闭或其它点击监听。