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

iOS 16 Safari自动聚焦特定条件表单元素 求非移除式解决方案

iOS 16 Safari 自动聚焦input元素问题的解决方案(无需移除input或pattern)

问题背景

在iOS 16.0的Safari浏览器中,满足以下条件时input元素会被自动聚焦,导致页面自动滚动、放大并唤起键盘:

  • input类型为type="number"或type="text"
  • 设置了pattern="\d*"
  • 容器元素的margin-top值约为48px(临界值未精确测试)

设置autocomplete="off"、autofocus="false"均无法解决该问题,且iOS 16之前版本无此现象,已在2台不同iPhone上验证。

解决方案(无需移除input或pattern)

方案1:JavaScript延迟失焦处理

利用setTimeout在页面加载完成后延迟将目标input失焦,避开Safari的自动聚焦逻辑:

window.addEventListener('load', function() {
  setTimeout(() => {
    const targetInput = document.querySelector('input[pattern="\\d*"]');
    if (targetInput && document.activeElement === targetInput) {
      targetInput.blur();
    }
  }, 100); // 可根据实际情况调整延迟时间
});

方案2:CSS调整容器定位替代margin-top

如果允许微调布局,可用padding-top或transform替代容器的margin-top,实现相同间距的同时避开触发条件:

/* 替换原有的margin-top:48px */
.container {
  padding-top: 48px;
  /* 或者使用transform */
  /* transform: translateY(48px); */
}

方案3:动态设置pattern属性

在页面加载完成后再给input添加pattern="\d*"属性,避免初始渲染时触发Safari的bug:

window.addEventListener('load', function() {
  const targetInputs = document.querySelectorAll('input[type="number"], input[type="text"]');
  targetInputs.forEach(input => {
    input.setAttribute('pattern', '\\d*');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:35:21