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

.NET MAUI Blazor:iOS端聚焦textarea时如何阻止键盘上推全屏?

.NET MAUI Blazor iOS 端阻止键盘顶起视图的解决方案

由于.NET MAUI Blazor的WebView基于原生容器封装,普通Web端的CSS/JS方案可能无法生效,以下是针对该场景的专属解决办法:

1. 原生iOS配置修改

在iOS项目的Info.plist中添加以下配置,禁用WebView的键盘自动调整行为:

<key>UIWebViewKeyboardDisplayRequiresUserAction</key>
<true/>
<key>WKWebViewConfiguration</key>
<dict>
    <key>scrollViewKeyboardDismissMode</key>
    <string>none</string>
    <key>scrollViewKeyboardShouldPersistTaps</key>
    <false/>
</dict>

2. Blazor页面CSS调整

针对textarea或其父容器设置样式,避免被键盘驱动的滚动影响:

  • 若textarea固定在页面底部,直接使用固定定位:
textarea {
    position: fixed;
    bottom: 20px;
    left: 20px;
    right: 20px;
    height: 120px;
    resize: none;
}
  • 若textarea在滚动容器内,禁用容器的自动滚动触发:
.scroll-container {
    overflow: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: auto;
}

3. JS交互辅助修复

在wwwroot/js目录创建keyboard-fix.js文件,添加以下代码:

window.preventKeyboardScroll = () => {
    const textareas = document.querySelectorAll('textarea');
    textareas.forEach(textarea => {
        textarea.addEventListener('focus', () => {
            document.body.style.position = 'fixed';
            document.body.style.top = `-${window.scrollY}px`;
        });
        textarea.addEventListener('blur', () => {
            const scrollOffset = parseInt(document.body.style.top || '0') * -1;
            document.body.style.position = '';
            document.body.style.top = '';
            window.scrollTo(0, scrollOffset);
        });
    });
}

然后在Blazor页面的生命周期方法中调用该JS函数:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("preventKeyboardScroll");
    }
}

上述方案结合了原生配置与Web端代码,能有效避免iOS键盘弹出时顶起视图的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:55:00