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

Chrome Mobile中alert弹窗后input.focus()无法正常工作的问题求助

问题分析与解决方案

这确实是Chrome Mobile的特定行为限制,并非你的代码逻辑错误。Chrome对原生alert这类系统级模态弹窗有特殊的焦点管理机制:弹窗关闭后,浏览器会保留自身的焦点状态,即便你调用input.focus(),输入框只能触发键盘弹出的视觉效果,但实际无法获得可交互的编辑焦点——这就是键盘弹出来却不能输入的原因。Firefox Mobile没有这个限制,所以能正常工作。

可行的解决方案

方案1:替换原生alert为自定义模态弹窗

放弃使用系统原生的alert,改用自定义的HTML/CSS模态框,这样可以完全掌控弹窗关闭后的焦点逻辑,避免Chrome的焦点锁定问题。

示例代码:

<!-- 自定义模态框 -->
<div id="customAlert" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); padding:20px; background:white; border:1px solid #ccc; z-index:9999;">
  <p>Some information</p>
  <button id="closeAlert">确定</button>
</div>

<input id="input" type="text">
<button id="button">Button</button>

<script>
const btn = document.getElementById('button')
const customAlert = document.getElementById('customAlert')
const closeAlertBtn = document.getElementById('closeAlert')
const input = document.getElementById('input')

btn.addEventListener('click', () => {
  customAlert.style.display = 'block'
})

closeAlertBtn.addEventListener('click', () => {
  customAlert.style.display = 'none'
  input.focus() // 弹窗关闭后直接聚焦,Chrome下可正常交互
})
</script>

方案2:延迟聚焦结合Chrome焦点修复

如果一定要用原生alert,可以尝试用setTimeout结合requestAnimationFrame来延迟聚焦,给Chrome足够的时间释放焦点锁定:

const btn = document.getElementById('button')
btn.addEventListener('click', () => {
    alert("Some information")
    setTimeout(() => {
        requestAnimationFrame(() => {
            const input = document.getElementById('input')
            input.focus()
            // 额外触发一次输入框的点击事件,强制激活编辑状态
            input.click()
        })
    }, 100)
})

这个方案的稳定性不如自定义弹窗,但部分场景下可以解决问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:15:44