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

移动端设置overflow:hidden后聚焦输入框页面仍滚动的解决办法

问题描述

我给页面添加了如下CSS代码,用来阻止移动端页面上下滚动:

body{
   height:100%;
   overflow:hidden;
}

但当聚焦页面中的输入框时,页面仍会出现上下移动的情况,请问如何解决这一问题?

附完整代码示例:

CSS代码

body {
  height: 100%;
  overflow: hidden;
}

HTML代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Login</title>

</head>

<body>
  <div class='container'>
    <form>
      <input type='text'>
    </form>
  </div>

</body>

</html>
解决方案

这是因为移动端浏览器在输入框聚焦时,会自动调整视口以保证输入框可见,即便body设置了overflow:hidden也会触发该行为。以下是几种可行的解决方法:

方法1:动态锁定页面位置

给html也添加上溢出限制,同时监听输入框的聚焦/失焦事件,手动锁定页面位置:

html, body {
  height: 100%;
  overflow: hidden;
}
const input = document.querySelector('input');
let scrollPosition = 0;

input.addEventListener('focus', () => {
  // 记录当前滚动位置
  scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
  // 固定页面位置
  document.body.style.position = 'fixed';
  document.body.style.top = `-${scrollPosition}px`;
});

input.addEventListener('blur', () => {
  // 恢复页面滚动和位置
  document.body.style.position = '';
  document.body.style.top = '';
  window.scrollTo(0, scrollPosition);
});

方法2:禁用触摸默认行为

在html和body上添加touch-action属性,直接禁用触摸相关的滚动行为:

html, body {
  height: 100%;
  overflow: hidden;
  touch-action: none;
}

注意:该属性会禁用所有触摸交互(比如长按选文本),如果需要保留部分交互,可改用touch-action: pan-x(仅允许横向滚动)这类更精细的取值。

方法3:优化视口与布局适配

修改视口标签,配合输入框布局调整,减少浏览器自动偏移的触发:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />

同时确保输入框处于页面上方区域,避免键盘弹出时浏览器需要大幅调整视口位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:09:24