使用 Blazor 从输入中获取选定的文本

phi*_*hil 5 blazor blazor-server-side

在 Blazor 的早期版本中,有一个带有和属性IHtmlInputElement的接口。selectionStartselectionEnd

谁能解释一下如何使用它们从 C# 中的文本输入控件中获取选定的文本?

更新 这是我到目前为止所拥有的。

@page "/selectedtext"
@inject IJSRuntime JsRuntime

<h3>TextSelection</h3>

<input type="text" placeholder="Type here" @ref="myTextInput"/>

<button class="btn btn-primary" @onclick="@(async () => await GetSelectionStart(myTextInput))"></button>

@code {
    public ElementReference myTextInput { get; set; }

    public async Task GetSelectionStart(ElementReference element)
    {
        int pos = await JsRuntime.InvokeAsync<int>("GetSelectedStart", element);
    }
}

// myscript.js
{
    getSelectedStart : function (element) {
        return element.selectionStart;
    }
}
Run Code Online (Sandbox Code Playgroud)

phi*_*hil 4

@page "/selectedtext"
@inject IJSRuntime JsRuntime

<h3>TextSelection</h3>

<input type="text" placeholder="Type here" @ref="myTextInput"/>

<button class="btn btn-primary" @onclick="@(async () => await GetSelectionStart(myTextInput))">Get Position</button>

@code {
    public ElementReference myTextInput { get; set; }

    public async Task GetSelectionStart(ElementReference element)
    {
        int pos = await JsRuntime.InvokeAsync<int>("getSelectedStart", element);
    }
}

// myscript.js
window.getSelectedStart = (element) => {
        return element.selectionStart;
    }

Run Code Online (Sandbox Code Playgroud)