c# - 在 Blazor 的开始屏幕上设置 InputText 焦点
问题描述
我正在使用 Visual Studio 2019 创建一个 Blazor PWA 应用程序。我使用 javascript 在启动和某些关键事件期间将焦点设置到 InputText 字段。
function focusInput(id){
document.getElementById(id).focus();
var tb = document.querySelector("#" + id);
if (tb.select) {
tb.select();
}
}
并像这样在我的代码中调用它
private string inputID = "user-id";
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await jsInterop.InvokeVoidAsync("focusInput", inputID);
}
这是剃须刀页面
<EditForm Model="@login" class="card card-body mt-2">
<div class="form-group row">
<label for="userid" class="col-sm-2 col-form-label">User ID</label>
<InputText id="@inputID" class="form-control" @bind-Value="@login.UserID" @onkeyup="(KeyboardEventArgs e) => KeyUpUserIDAsync(e)"/>
</div>
<div class="form-group row">
<label for="message" class="col-sm-2 col-form-label">Message</label>
<InputTextArea id="textarea-message" class="form-control" @bind-Value="@errorMessage" />
</div>
</EditForm>
它工作得很好,除非我运行它并加载第一页,即登录页面。焦点不是在字段中,而是留在 URL 栏中。如果我刷新页面 InputeText 获得焦点。请注意,我登录后导航到的所有其他页面都没有这个问题。只是初始页面。我写信给控制台以确保它被调用了。我也尝试使用自动对焦属性,但它也不起作用。
解决方案
我可以按照此处提供的解决方案使您的代码正常工作:
索引剃刀
@page "/"
@inject IJSRuntime JSRuntime
<EditForm Model="@login" class="card card-body mt-2">
<div class="form-group row">
<label for="userid" class="col-sm-2 col-form-label">User ID</label>
<InputText id="@inputID" class="form-control" @bind-
Value="@login.UserID" @onkeyup="(KeyboardEventArgs e) =>
KeyUpUserIDAsync(e)" />
</div>
<div class="form-group row">
<label for="message" class="col-sm-2 col-form-
label">Message</label>
<InputTextArea id="textarea-message" class="form-control" @bind-
Value="@errorMessage" />
</div>
</EditForm>
@code {
public class LoginModel
{
public string UserID { get; set; }
}
public LoginModel login = new();
public string inputID = "user-id";
public string errorMessage = null;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("focusElement", inputID);
}
}
async Task KeyUpUserIDAsync(KeyboardEventArgs e)
{
}
}
_Host.cshtml
<script>
function focusElement(id) {
const element = document.getElementById(id);
element.focus();
}
</script>
我多次运行该应用程序,每次加载登录输入时都会立即获得焦点,而无需我刷新页面。
推荐阅读
- php - 无法在外部 php 文件上加载多个 WordPress 网站
- anaconda - conda:分两步进行以避免冲突
- spring-boot - 对 HERE API 的地理编码请求随机失败
- c# - 如何仅获取数组 MongoDb 中的特定列表 - C#
- docker - docker 中的 OCI 运行时(container_linux.go:348)错误
- c# - 如何从 GraphQL 模式生成 C# 类型
- vb.net - 更新 CellClick 上的 DataGridViewCheckBoxColumn 复选框
- python - 烧瓶保持活动连接请求失败
- ios - Xcode:AccessoryType.checkmark 将其他视图推向左侧
- excel - 如何循环直到单元格为空