如何为所有可交互元素添加 `outline-offset`?
解读
面试官想知道两件事:
- 你是否了解「可交互元素」在 CSS 层面的真实范围——不仅限于
a、button、input,还包括[tabindex]、[contenteditable]、<summary>等; - 你是否能用 PostCSS 的 AST 能力「一次性、无侵入、可配置」地完成批量注入,而不是手写一堆选择器。
国内项目普遍要过「无障碍抽检」与「政府/金融合规审计」,outline-offset 是必检项;同时 UI 同学又要求「不要动我原来的样式」。因此「自动化、可灰度、可回滚」是硬需求,也是面试官的打分点。
知识点
- PostCSS 插件七步骨架:
module.exports = (opts = {}) => { return { postcssPlugin: '插件名', Rule(node, helpers) { ... } } } - 解析期钩子:Rule、Declaration、AtRule;遍历期 helpers:list、string、vendor。
- 可交互元素全集(WCAG 2.1 + 国内监管实践):
a, button, input, select, textarea, summary, [tabindex]:not([tabindex="-1"]), [contenteditable="true"], audio[controls], video[controls], iframe, object, embed, svg a, canvas[tabindex] - 去重与合并:利用
node.selector.split(',').map(s => s.trim())打散后去重,再合并回一条 Rule,减少渲染层选择器压力。 - 配置化:支持
opts.offset、opts.skipSelector、opts.preserve三个参数,方便在不同业务线开启不同偏移量,或保留已有 outline-offset。 - Sourcemap 与压缩:PostCSS 默认携带 sourcemap,面试时要主动提及「不破坏原有行列号」;若团队用 cssnano,需把本插件置于压缩之前,防止被误删。
答案
「写一个 PostCSS 插件,在 AST 层面插入一条合并后的规则」是最稳妥的方案。核心代码如下(可直接在 vite.config.ts 或 postcss.config.js 里使用):
// postcss-interactive-offset.js
module.exports = (opts = {}) => {
const {
offset = '4px',
skipSelector = () => false,
preserve = false
} = opts;
return {
postcssPlugin: 'postcss-interactive-offset',
Once(root, { Rule }) {
// 1. 全集选择器
const interactiveSelector = [
'a', 'button', 'input', 'select', 'textarea', 'summary',
'[tabindex]:not([tabindex="-1"])',
'[contenteditable="true"]',
'audio[controls]', 'video[controls]', 'iframe', 'object', 'embed',
'svg a', 'canvas[tabindex]'
].join(', ');
// 2. 跳过开关
if (skipSelector(interactiveSelector)) return;
// 3. 查找是否已存在相同选择器规则
let rule;
root.walkRules(interactiveSelector, r => {
if (r.selector === interactiveSelector) rule = r;
});
// 4. 已存在且要求保留则直接返回
if (rule && preserve) return;
// 5. 不存在则新建,存在则复用
if (!rule) {
rule = new Rule({ selector: interactiveSelector });
root.append(rule);
}
// 6. 插入或更新声明
let decl = rule.nodes.find(d => d.prop === 'outline-offset');
if (!decl) {
decl = rule.append({ prop: 'outline-offset', value: offset });
} else if (!preserve) {
decl.value = offset;
}
}
};
};
module.exports.postcss = true;
使用示例(postcss.config.js):
module.exports = {
plugins: [
require('./postcss-interactive-offset')({
offset: '0.25rem',
preserve: false,
skipSelector: (sel) => process.env.NODE_ENV === 'production' && sel.includes('iframe')
}),
require('autoprefixer'),
require('cssnano')
]
};
亮点:
- 只生成一条 Rule,性能最优;
- 支持灰度(skipSelector)、支持多环境差异化;
- 不破坏原有 sourcemap,审计可回溯;
- 若 UI 已自行写过 outline-offset,可通过
preserve:true保留原值,避免冲突。
拓展思考
- 如果设计稿要求「焦点时才有偏移」,可把插件升级为「双态」:默认
outline-offset:0,再追加:focus-visible伪类并赋偏移值;同时配合postcss-focus-visible做 polyfill,可兼容 IE11。 - 在微前端场景,子应用可能异步挂载,DOM 结构不可预期。可把该插件封装成 Vite/Rollup 的
generateBundle钩子,在产物最后阶段再扫描一次 CSS,确保动态插入的交互元素也能命中。 - 国内大型中台常要求「一键换肤」,outline-offset 颜色需要随主题变量变化。此时可把
offset改为var(--outline-offset, 4px),再由 CSS 变量在运行时切换,插件只负责注入声明,不管具体值。 - 面试加分项:主动提到「我们还在 CI 里加了 stylelint-plugin-a11y,若检测到可交互元素缺失 outline 相关属性,就阻断 MR」,体现你对工程化与无障碍合规的闭环思考。