如何检测并警告 viewport 中不可点击的 44×44 px 区域?
解读
国内前端面试常把“可点击区域≥44×44 px”作为无障碍与移动端体验硬指标。Cypress 运行在浏览器内,天然能拿到真实渲染尺寸与事件层遮挡关系,但默认不会主动量化学术规范。题目要求“检测并警告”,意味着:
- 遍历所有可交互元素(button、a、input、[role="button"] 等);
- 计算其在viewport 中的实际尺寸(排除 transform、scale 后的视觉尺寸);
- 若宽或高<44 px,或元素被祖先 overflow 隐藏、被兄弟节点遮挡导致不可点击,立即在 GUI 与命令行给出中文警告;
- 以自定义命令形式集成,保持 Cypress 的“秒级反馈”体验。
知识点
- Element.getBoundingClientRect() 与 window.getComputedStyle() 获取真实渲染尺寸
- elementFromPoint(x,y) 与 pointer-events 判断遮挡关系
- Cypress Custom Commands 与 cy.window()、cy.document() 的无头与 headed 一致性
- chai 插件扩展,将警告写入 Cypress.Log 与 终端,满足国内 CI 质量门禁
- 44×44 px 规范出自 WCAG 2.5.5 与 工信部 APP 适老化通用设计规范,面试答出“国标”可加分
答案
- 在 cypress/support/index.js 注册自定义命令:
Cypress.Commands.add('check44x44', () => {
cy.window().then((win) => {
const logs = [];
const selector = [
'button','a','input','select','textarea','[role="button"]','[tabindex]:not([tabindex="-1"])'
].join(',');
cy.document().then((doc) => {
const elems = Array.from(doc.querySelectorAll(selector));
elems.forEach((el) => {
const rect = el.getBoundingClientRect();
const visWidth = rect.width;
const visHeight = rect.height;
// 尺寸不足
if (visWidth < 44 || visHeight < 44) {
logs.push(`⚠️ 元素 <${el.tagName.toLowerCase()}> 实际尺寸 ${visWidth}×${visHeight}px 小于 44×44`);
return;
}
// 遮挡检测:取中心点
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
const topEl = win.document.elementFromPoint(x, y);
if (!el.contains(topEl) && !topEl.contains(el)) {
logs.push(`⚠️ 元素 <${el.tagName.toLowerCase()}> 在 (${x},${y}) 被遮挡,可能不可点击`);
}
});
// 统一输出,避免多次 cy.log 打断快照
if (logs.length) {
cy.task('log44', logs); // 终端中文警告
cy.wrap(logs).each((msg) => Cypress.log({ name: '44×44', message: msg }));
} else {
Cypress.log({ name: '44×44', message: '✅ 所有可交互元素均满足 44×44 可点击规范' });
}
});
});
});
- 在 cypress/plugins/index.js 添加终端打印:
module.exports = (on, config) => {
on('task', {
log44(msgs) {
console.warn('\n========== 44×44 规范检查 ==========');
msgs.forEach(m => console.warn(m));
return null;
}
});
};
- 测试用例中调用:
describe('国标可点击区域检测', () => {
it('应满足 44×44 px 规范', () => {
cy.visit('/');
cy.check44x44(); // 一键检测并警告
});
});
运行后,GUI 右侧命令日志与国内 Jenkins/钉钉群终端都会中文高亮警告,满足面试官“看得见、管得住”的要求。
拓展思考
- 若项目使用 CSS scale/zoom,需在计算前乘以 getComputedStyle(el).transform 的矩阵系数,避免“视觉合格、数值不合格”的假阴性。
- 对固定定位或虚拟列表内元素,可结合 IntersectionObserver 在 cy.window() 中预筛“可视子集”,减少遍历开销,体现性能意识。
- 把 check44x44 封装为 npm 私有包,通过 cypress.config.js 的 setupNodeEvents 自动注入,可在多条业务线强制落地国标,面试时提及“工程化落地”可进一步加分。