如何用 less 变量统一控制 tabindex 的可见样式?

解读

面试官真正想考察的是“你是否能把 Less 的变量体系、作用域、混合(Mixin)与 CSS 的可访问性规范结合起来,解决‘焦点可见’这一高频需求”。
国内中大型企业(阿里、腾讯、字节、美团等)的组件库统一要求:

  1. 所有可聚焦元素在获得焦点时必须高亮,且高亮颜色随主题包变化;
  2. 不允许在业务代码里硬编码 outline、box-shadow、伪元素等具体值;
  3. 必须支持暗色/亮色双主题一键切换。
    因此,回答要体现“变量抽象 → 混合封装 → 主题切换 → 编译输出”的完整闭环,并给出可落地的文件结构。

知识点

  1. Less 变量定义与延迟求值(lazy evaluation)
  2. 默认变量(@variable: defaultValue;)与主题覆盖机制
  3. 参数化混合(.mixin(@param: default))与作用域隔离
  4. & 父选择器在伪类与伪元素中的用法
  5. CSS 焦点伪类 :focus-visible 与 :focus 的差异化策略(W3C 规范 + 国内合规要求)
  6. 主题切换方案:CSS 变量(var())与 Less 变量的分工——Less 变量负责“编译期定值”,CSS 变量负责“运行时切换”
  7. 编译链:lessc → PostCSS(autoprefixer)→ 产物压缩,保证 :focus-visible 的兼容性前缀自动补齐
  8. 企业级目录规范:variables.less → theme/.less → mixins/utility.less → components/.less

答案

  1. 建立全局变量层 src/style/variables.less
// 焦点可见统一变量
@tabindex-outline-width: 2px;
@tabindex-outline-style: solid;
@tabindex-outline-color: #1890ff;   // 默认主色
@tabindex-outline-offset: 2px;
@tabindex-shadow-blur: 4px;
@tabindex-shadow-color: fade(@tabindex-outline-color, 30%);
  1. 提供主题覆盖文件 src/style/theme/dark.less
// 暗色主题仅覆盖颜色
@tabindex-outline-color: #3086ff;
@tabindex-shadow-color: fade(@tabindex-outline-color, 50%);
  1. 封装混合 src/style/mixins/focus.less
// 公共焦点可见混合
.focus-visible(@color: @tabindex-outline-color,
               @width: @tabindex-outline-width,
               @offset: @tabindex-outline-offset) {
  outline: @width @tabindex-outline-style @color;
  outline-offset: @offset;
  box-shadow: 0 0 @tabindex-shadow-blur @tabindex-shadow-color;
  // 兼容旧浏览器,提供降级
  &:focus {
    outline: @width @tabindex-outline-style @color;
    outline-offset: @offset;
  }
  // 现代浏览器优先使用 :focus-visible
  &:focus-visible {
    outline: @width @tabindex-outline-style @color;
    outline-offset: @offset;
    box-shadow: 0 0 @tabindex-shadow-blur @tabindex-shadow-color;
  }
  // 强制隐藏 :focus 的默认轮廓,避免双影
  &:focus:not(:focus-visible) {
    outline: none;
    box-shadow: none;
  }
}
  1. 业务组件中统一调用 src/components/button.less
@import (reference) "../../style/variables.less";
@import (reference) "../../style/mixins/focus.less";

.btn {
  // 其他样式略
  .focus-visible();   // 一行搞定,颜色随主题变化
}
  1. 编译脚本(package.json 片段,符合国内 CI 规范)
"build:less": "lessc src/style/index.less dist/index.css --js && postcss dist/index.css --use autoprefixer --replace"
  1. 主题切换
    在运行时使用 <body data-theme="dark"> 切换主题,只需在入口文件动态引入 theme/dark.less,重新编译即可,无需改动业务代码。

拓展思考

  1. 如果产品要求“高对比度模式”下自动加粗焦点环,如何不改混合签名?
    答:在 .focus-visible 内部使用媒体查询 @media (prefers-contrast: high) 动态放大 @width,保持调用层零感知。
  2. 当组件库被多方复用,如何防止变量名污染?
    答:采用 Less 的“命名空间变量”技巧 #focus { @outline-color: xxx; },通过 #focus::outline-color 引用,实现模块级隔离。
  3. 未来迁移到 CSS 变量是否成本高?
    答:提前在混合里预留 var(--tabindex-color, @tabindex-outline-color) 的写法,编译期 Less 变量做兜底,运行时 CSS 变量做覆盖,可实现“零成本热切换”。