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

移动端Chrome虚拟键盘开启时滚动,fixed定位输入框失效

解决方案

1. 用动态视口单位替代100vh

移动端Chrome弹出虚拟键盘时,100vh会把键盘高度也算入视口高度,导致容器布局计算错误。换成100dvh(动态视口高度)可让容器高度适配当前实际可用的屏幕空间:

.chat-container {
   width: 100%;
   top: 0;
   left: 0;
   height: 100dvh; /* 替换原有的100vh */
   bottom: 0;
   overflow: hidden;
   border-radius: 0;
   box-shadow: none;
   position: relative;
   z-index: 1;
}

2. 调整输入框定位逻辑

把输入框的fixed定位改为基于父容器的absolute定位,确保它始终贴合父容器底部:

.input-field {
   position: absolute; /* 替换原有的fixed */
   bottom: 0;
   width: 100%;
   z-index: 2;
}

父容器.chat-container已经设置了position: relative且高度为100dvh,输入框会相对父容器底部固定,不受页面滚动或键盘弹出的异常影响。

3. 监听视口变化动态调整(备选方案)

如果动态视口单位无法满足需求,可在React中监听visualViewport变化,实时修正输入框位置:

import { useEffect } from 'react';

const ChatInput = () => {
  useEffect(() => {
    const adjustInputPosition = () => {
      const inputEl = document.querySelector('.input-field');
      if (!inputEl) return;
      // 根据可视视口高度计算输入框底部偏移
      const viewportDiff = window.innerHeight - (window.visualViewport?.height || window.innerHeight);
      inputEl.style.bottom = `${viewportDiff}px`;
    };

    window.visualViewport?.addEventListener('resize', adjustInputPosition);
    return () => {
      window.visualViewport?.removeEventListener('resize', adjustInputPosition);
    };
  }, []);

  // 组件原有逻辑...
};

4. 优化Viewport Meta标签

确保index.html中的viewport配置正确,避免浏览器布局偏移:

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:50:11