ios上fixed底部输入框被键盘遮挡的简单解决办法

文章讨论了在iOS设备上,使用position:fixed;时遇到的问题,当输入框在页面底部,弹出软键盘会遮挡输入框。为解决此问题,文中提供了一个JavaScript解决方案,即在textarea获取焦点时,延迟滚动到页面底部。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ios据说不支持position: fixed;

在安卓上面,点击页面底部的输入框,软键盘弹出,页面移动上移。

而ios上面,点击页面底部输入框,软键盘弹出,输入框看不到了。。。

var u = navigator.userAgent, app = navigator.appVersion;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isiOS) {
    $('textarea').focus(function () {
        window.setTimeout('scrollBottom()', 500);
    });
}
function scrollBottom() {
    window.scrollTo(0, $('body').height());
}

当输入框获得焦点时候,等待500毫秒(键盘弹出动画时间)滚动到页面底部。
引用地址:

https://codeleading.com/article/86743161474/

### 问题分析 在 UniApp 开发中,移动端 H5 页面或小程序页面常常遇到软键盘弹出时遮挡底部输入框的问题。这种现象通常由以下几个原因造成: - **页面布局未动态调整**:当软键盘弹出时,页面高度发生变化,但布局未能随之调整。 - **fixed 定位元素的定位异常**:底部输入框使用 `position: fixed` 定位时,在某些设备上(如 iOS)无法正确响应软键盘弹出导致的位置变化。 - **缺乏对软键盘事件的监听和处理机制**:没有根据软键盘弹出/收起事件来动态调整输入框位置。 ### 解决方案 #### 1. 使用 `adjust-position` 和 `cursor-spacing` 属性 UniApp 提供了原生输入框的属性支持,可以自动调整输入框的位置以避免被软键盘遮挡。例如: ```html <input type="text" placeholder="请输入内容" :adjust-position="true" cursor-spacing="30" @input="onInput" /> ``` 其中: - `adjust-position="true"` 表示软键盘弹出时自动调整页面位置,使输入框可见。 - `cursor-spacing="30"` 设置光标与软键盘之间的距离,单位为 px[^2]。 #### 2. 监听软键盘弹出事件并手动调整样式 通过监听 `@focus` 和 `@blur` 事件,结合系统信息 API 获取软键盘高度,并动态调整输入框的 `bottom` 值。 ```html <template> <view class="container"> <scroll-view scroll-y style="flex-grow: 1;"> <!-- 页面内容 --> </scroll-view> <view class="input-box" :style="{ bottom: inputBottom + 'px' }"> <input type="text" placeholder="请输入内容" @focus="onFocus" @blur="onBlur" /> </view> </view> </template> <script> export default { data() { return { inputBottom: 0 }; }, methods: { onFocus(e) { if (e.detail && e.detail.height) { this.inputBottom = e.detail.height; } }, onBlur() { this.inputBottom = 0; } } }; </script> <style scoped> .container { display: flex; flex-direction: column; height: 100vh; } .input-box { position: fixed; left: 0; right: 0; bottom: 0; padding: 10px; background-color: #fff; transition: bottom 0.3s ease-in-out; } </style> ``` 此方法通过设置 `input-box` 的 `bottom` 值为软键盘高度,使得输入框始终位于软键盘上方,从而避免遮挡[^3]。 ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值