⌨️ 软键盘处理

软键盘弹出是移动端 Web 开发中最头疼的问题之一,主要涉及页面顶起、布局错乱、滚动异常等问题。

iOS 与 Android 的差异

行为iOS SafariAndroid Chrome
键盘弹出页面不压缩,键盘覆盖在页面上方可视区域缩小,页面可能被压缩
页面高度不变,window.innerHeight 不变变小,window.innerHeight 变化
输入框聚焦不会自动滚入视野自动 scrollIntoView
键盘收起页面可能有空白残留恢复正常

监听键盘弹出与收起

// ===== 监听软键盘状态 =====
let lastHeight = window.innerHeight;

window.addEventListener('resize', () => {
  const currentHeight = window.innerHeight;
  const diff = lastHeight - currentHeight;

  if (diff > 100) {
    console.log('⌨️ 键盘弹出', diff + 'px');
    // 处理键盘弹出:如固定底部按钮上移
    document.querySelector('.fixed-bottom')
      .style.bottom = diff + 'px';
  } else if (diff < -50) {
    console.log('⬆️ 键盘收起');
    document.querySelector('.fixed-bottom')
      .style.bottom = '0';
  }
  lastHeight = currentHeight;
});

常见问题与解决方案

/* ===== 软键盘相关 CSS 处理 ===== */

/* 问题 1:键盘弹出后页面滚动到顶部 */
/* 解决:输入框聚焦时手动滚动 */
input.addEventListener('focus', (e) => {
  setTimeout(() => {
    e.target.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }, 300); // iOS 需要延迟
});

/* 问题 2:iOS 键盘收起后页面留白 */
/* 解决:失焦时滚动回顶部 */
input.addEventListener('blur', () => {
  setTimeout(() => {
    window.scrollTo(0, 0);
    // 或触发一下 body 重绘
    document.body.scrollTop = 0;
  }, 100);
});

/* 问题 3:固定定位元素被键盘顶起 */
/* 解决:键盘弹出时改为 absolute 或隐藏 */
@media (max-height: 500px) {
  .fixed-bottom {
    position: absolute;
  }
}
⚠️ 移动端表单最佳实践
  • 表单尽量放在页面中部以上,避免键盘遮挡
  • 底部固定按钮在键盘弹出时应隐藏或上移
  • iOS 上 <input>font-size 至少 16px,否则聚焦时会缩放
  • 避免在 input 聚焦时执行耗时操作