You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

伪类:focus-within在Safari浏览器中失效问题排查

问题:Safari 15.6.1中按钮的:focus-within样式不生效

以下代码在Chrome和Firefox中点击按钮后文字会变红,但在Safari 15.6.1版本中无法实现预期效果:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #my-button:focus-within {
      color: red;
    }
  </style>
</head>
<body>
  <button id="my-button" tabindex="0">item2</button>
</body>
</html>

问题原因

Safari 15.6.1对:focus-within伪类的实现存在兼容性局限:它认为:focus-within仅适用于包含焦点元素的父容器,而不会作用于元素自身。按钮本身就是可聚焦元素,点击后自身获得焦点,但旧版Safari不会因此触发自身的:focus-within状态;而Chrome和Firefox则支持元素自身作为焦点元素时触发:focus-within。

解决办法

方案1:改用:focus伪类(推荐)

因为按钮本身是可聚焦元素,直接使用:focus就能精准匹配点击后的焦点状态,兼容性更好:

#my-button:focus {
  color: red;
}

方案2:给按钮添加父容器(保留:focus-within逻辑)

如果后续按钮内部会新增子元素,需要依赖:focus-within的父容器匹配逻辑,可以给按钮套一层父元素,将样式转移到父元素的:focus-within上:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .button-wrap:focus-within {
      color: red;
    }
  </style>
</head>
<body>
  <div class="button-wrap">
    <button id="my-button" tabindex="0">item2</button>
  </div>
</body>
</html>

内容的提问来源于stack exchange,提问作者trueToastedCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:02:54