首页 > 解决方案 > 在 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 获得焦点。请注意,我登录后导航到的所有其他页面都没有这个问题。只是初始页面。我写信给控制台以确保它被调用了。我也尝试使用自动对焦属性,但它也不起作用。

标签: c#blazorprogressive-web-apps

解决方案


我可以按照此处提供的解决方案使您的代码正常工作:

如何将焦点设置到 InputText 元素?

索引剃刀

@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>

我多次运行该应用程序,每次加载登录输入时都会立即获得焦点,而无需我刷新页面。


推荐阅读