Bootstrap4 信息提示框
核对 Bootstrap 4 8 种语义信息提示框配色、.alert-link 自适应链接色、.alert-dismissible 关闭交互与 HTML 实体 ×,以及 .fade.show 淡出过渡实测。
学完这一章,你能够
- 核对 Bootstrap 4 8 种语义信息提示框配色、.alert-link 自适应链接色、.alert-dismissible 关闭交互与 HTML 实体 ×,以及 .fade.show 淡出过渡实测。
语义信息提示框 .alert-*
Bootstrap 4 通过基类 `.alert` 搭配 8 种语义修饰类(`.alert-success`、`.alert-info`、`.alert-warning`、`.alert-danger`、`.alert-primary`、`.alert-secondary`、`.alert-light`、`.alert-dark`)快速生成状态反馈横幅。本站离线 Chromium 实测确认所有提示框统一采用 `12px 20px` 内边距与 `4px` 圆角,并分别渲染配套的背景、边框与文字 RGB 配色(例如 `.alert-success` 为底色 `rgb(212, 237, 218)`、边框 `rgb(195, 230, 203)`、文字 `rgb(21, 87, 36)`;`.alert-danger` 为底色 `rgb(248, 215, 218)`、边框 `rgb(245, 198, 203)`、文字 `rgb(114, 28, 36)`)。
提示框内的匹配链接 .alert-link
若在提示框中嵌入超链接,为 `<a>` 添加 `.alert-link` 可自动加粗(`font-weight: 700`)并匹配当前提示框的深色系配色,避免默认蓝色链接在红、黄或绿底上显得突兀。本站实测 `.alert-link` 在 `.alert-success`、`.alert-warning`、`.alert-danger` 与 `.alert-primary` 中分别呈现 `rgb(11, 46, 19)`、`rgb(83, 63, 3)`、`rgb(73, 18, 23)` 与 `rgb(0, 39, 82)`。
可关闭提示框与淡入淡出动画
要支持用户手动关闭提示框,需在容器上添加 `.alert-dismissible`(右侧预留 `4rem` 即 `64px` 内边距避免文字遮挡关闭键),并在关闭按钮上添加 `class="close"` 与 `data-dismiss="alert"`。关闭图标应使用 HTML 字符实体 `×`(对应 Unicode 乘号 `×`,编码 `215`),而不要直接写英文字母 `x`。本站使用离线关闭交互脚本在 Chromium 中真实点击关闭按钮后,提示框节点即从 DOM 中移除。
为关闭过程增加平滑过渡时,在提示框上额外叠加 `.fade.show` 类:初始处于可见状态(`opacity: 1`、`transition-property: opacity`),点击关闭按钮先移除 `.show` 触发透明淡出动画,再于过渡结束后从 DOM 移除元素。生产环境中该交互由 Bootstrap 4 的 JS 插件(依赖 jQuery)驱动。
离线验证 Bootstrap 4 语义提示框、.alert-link 配色与可关闭淡出交互
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 09 (alerts)."""
import json
from playwright.sync_api import sync_playwright
BS4_ALERT_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 16px; font-family: sans-serif; font-size: 1rem; line-height: 1.5; color: #212529; background: #fff; }
.alert { position: relative; padding: 0.75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: 0.25rem; }
.alert-link { font-weight: 700; text-decoration: none; }
.alert-dismissible { padding-right: 4rem; }
.alert-dismissible .close { position: absolute; top: 0; right: 0; padding: 0.75rem 1.25rem; color: inherit; background: transparent; border: 0; font-size: 1.5rem; font-weight: 700; line-height: 1; opacity: 0.5; cursor: pointer; }
.alert-primary { color: #004085; background-color: #cce5ff; border-color: #b8daff; }
.alert-primary .alert-link { color: #002752; }
.alert-secondary { color: #383d41; background-color: #e2e3e5; border-color: #d6d8db; }
.alert-secondary .alert-link { color: #202326; }
.alert-success { color: #155724; background-color: #d4edda; border-color: #c3e6cb; }
.alert-success .alert-link { color: #0b2e13; }
.alert-info { color: #0c5460; background-color: #d1ecf1; border-color: #bee5eb; }
.alert-info .alert-link { color: #062c33; }
.alert-warning { color: #856404; background-color: #fff3cd; border-color: #ffeeba; }
.alert-warning .alert-link { color: #533f03; }
.alert-danger { color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; }
.alert-danger .alert-link { color: #491217; }
.alert-light { color: #818182; background-color: #fefefe; border-color: #fdfdfe; }
.alert-light .alert-link { color: #686868; }
.alert-dark { color: #1b1e21; background-color: #d6d8d9; border-color: #c6c8ca; }
.alert-dark .alert-link { color: #040505; }
.fade { transition: opacity 0.15s linear; }
.fade:not(.show) { opacity: 0; }
"""
DISMISS_JS = """
document.addEventListener('click', (e) => {
const btn = e.target.closest('[data-dismiss="alert"]');
if (!btn) return;
const box = btn.closest('.alert');
if (!box) return;
if (box.classList.contains('fade')) {
box.classList.remove('show');
window.__fadeDismissStage = getComputedStyle(box).opacity;
setTimeout(() => box.remove(), 40);
} else {
box.remove();
}
});
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_ALERT_CSS}</style></head>
<body>
<div id="palette">
<div class="alert alert-success"><strong>成功!</strong> 提示 <a href="#" class="alert-link">链接</a></div>
<div class="alert alert-info"><strong>信息!</strong> 提示</div>
<div class="alert alert-warning"><strong>警告!</strong> 提示 <a href="#" class="alert-link">链接</a></div>
<div class="alert alert-danger"><strong>错误!</strong> 提示 <a href="#" class="alert-link">链接</a></div>
<div class="alert alert-primary"><strong>首选!</strong> 提示 <a href="#" class="alert-link">链接</a></div>
<div class="alert alert-secondary"><strong>次要!</strong> 提示</div>
<div class="alert alert-light"><strong>浅色!</strong> 提示</div>
<div class="alert alert-dark"><strong>深色!</strong> 提示</div>
</div>
<div id="dismiss-plain" class="alert alert-success alert-dismissible">
<button id="btn-close-plain" type="button" class="close" data-dismiss="alert">×</button>
<strong>成功!</strong> 可直接关闭的提示框。
</div>
<div id="dismiss-fade" class="alert alert-danger alert-dismissible fade show">
<button id="btn-close-fade" type="button" class="close" data-dismiss="alert">×</button>
<strong>错误!</strong> 带淡出过渡的提示框。
</div>
<script>{DISMISS_JS}</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)
page = browser.new_page(viewport={"width": 900, "height": 900})
page.set_content(HTML_PAGE)
# Case 1: alert_contextual_colors
pal = page.evaluate("""() => {
const out = {};
for (const el of document.querySelectorAll('#palette > .alert')) {
const variant = el.className.split(' ')[1];
const s = getComputedStyle(el);
out[variant] = { bg: s.backgroundColor, border: s.borderTopColor, color: s.color };
}
const base = getComputedStyle(document.querySelector('#palette > .alert'));
return {
padding: base.paddingTop + ' ' + base.paddingRight,
radius: base.borderRadius,
variants: out,
};
}""")
expected_1 = {
"padding": "12px 20px",
"radius": "4px",
"variants": {
"alert-success": {"bg": "rgb(212, 237, 218)", "border": "rgb(195, 230, 203)", "color": "rgb(21, 87, 36)"},
"alert-info": {"bg": "rgb(209, 236, 241)", "border": "rgb(190, 229, 235)", "color": "rgb(12, 84, 96)"},
"alert-warning": {"bg": "rgb(255, 243, 205)", "border": "rgb(255, 238, 186)", "color": "rgb(133, 100, 4)"},
"alert-danger": {"bg": "rgb(248, 215, 218)", "border": "rgb(245, 198, 203)", "color": "rgb(114, 28, 36)"},
"alert-primary": {"bg": "rgb(204, 229, 255)", "border": "rgb(184, 218, 255)", "color": "rgb(0, 64, 133)"},
"alert-secondary": {"bg": "rgb(226, 227, 229)", "border": "rgb(214, 216, 219)", "color": "rgb(56, 61, 65)"},
"alert-light": {"bg": "rgb(254, 254, 254)", "border": "rgb(253, 253, 254)", "color": "rgb(129, 129, 130)"},
"alert-dark": {"bg": "rgb(214, 216, 217)", "border": "rgb(198, 200, 202)", "color": "rgb(27, 30, 33)"},
},
}
cases.append(dict(name="alert_contextual_colors", passed=(pal == expected_1), expected=expected_1, actual=pal))
# Case 2: alert_link_matching
links = page.evaluate("""() => {
const out = {};
for (const cls of ['alert-success', 'alert-warning', 'alert-danger', 'alert-primary']) {
const a = document.querySelector('.' + cls + ' .alert-link');
const s = getComputedStyle(a);
out[cls] = { color: s.color, weight: s.fontWeight };
}
return out;
}""")
expected_2 = {
"alert-success": {"color": "rgb(11, 46, 19)", "weight": "700"},
"alert-warning": {"color": "rgb(83, 63, 3)", "weight": "700"},
"alert-danger": {"color": "rgb(73, 18, 23)", "weight": "700"},
"alert-primary": {"color": "rgb(0, 39, 82)", "weight": "700"},
}
cases.append(dict(name="alert_link_matching", passed=(links == expected_2), expected=expected_2, actual=links))
# Case 3: alert_dismissible_click_close
before_plain = page.evaluate("""() => {
const box = document.getElementById('dismiss-plain');
const btn = document.getElementById('btn-close-plain');
return {
padding_right: getComputedStyle(box).paddingRight,
close_char_code: btn.textContent.charCodeAt(0),
close_is_not_ascii_x: btn.textContent !== 'x',
exists_before: !!box,
};
}""")
page.click("#btn-close-plain")
exists_after_plain = page.evaluate("() => !!document.getElementById('dismiss-plain')")
actual_3 = {**before_plain, "exists_after": exists_after_plain}
expected_3 = {
"padding_right": "64px",
"close_char_code": 215,
"close_is_not_ascii_x": True,
"exists_before": True,
"exists_after": False,
}
cases.append(dict(name="alert_dismissible_click_close", passed=(actual_3 == expected_3), expected=expected_3, actual=actual_3))
# Case 4: alert_fade_show_transition
before_fade = page.evaluate("""() => {
const box = document.getElementById('dismiss-fade');
const s = getComputedStyle(box);
return {
initial_opacity: s.opacity,
transition_prop: s.transitionProperty,
has_show: box.classList.contains('show'),
};
}""")
page.click("#btn-close-fade")
page.wait_for_function("() => !document.getElementById('dismiss-fade')")
actual_4 = {**before_fade, "removed_after_fade": True}
expected_4 = {
"initial_opacity": "1",
"transition_prop": "opacity",
"has_show": True,
"removed_after_fade": True,
}
cases.append(dict(name="alert_fade_show_transition", passed=(actual_4 == expected_4), expected=expected_4, actual=actual_4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 8 种 .alert-* 颜色、.alert-link 加粗配色、.alert-dismissible 64px 右内边距与 × 字符编码 215、真实点击关闭 DOM 移除,以及 .fade.show 透明度过渡。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:35c1717558f8f0ee55987aede6f5014ba18e407446aa34690c6b24664c64d849
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:78aa907f5da5a43557f7207a18934c1793026f991e25cf24de7df799d4fe0980
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
关闭提示框时 .alert-dismissible、data-dismiss="alert" 与 .fade.show 各自起什么作用?为何推荐用 × 代替字母 x?
展开参考解答
.alert-dismissible 为右上角关闭按钮预留右侧内边距与定位基准,data-dismiss="alert" 声明点击触发关闭行为,.fade.show 负责提供透明度淡出过渡;× 渲染的是标准对称乘号 ×(Unicode 215),视觉形态优于不对称的英文字母 x。