CODEKILLER

반응형

아래의 스크립트 함수는 포커싱을 담당할 Javascript함수입니다.

window.SetElementFocus = function (element) {
    element.focus();
    return element === true;
}

window.SetFocusByElementId = function (elementId) {
    var element = document.getElementById(elementId);
    element.focus();
    return element === true;
}

 

위의 Javascript 함수를 C#에서 이용하여 포커싱을 하시면 되는데요.

IJSRuntime를 이용하여 InvokeAsync 인자에 Javascript함수명을 넣어서 

자바스크립트 함수를 호출할 수 있습니다.

...
<input type="text" @ref="Input1" placeholder="Input 1" id="input1" />
<input type="text" @ref="Input2" placeholder="Input 2" id="input2" />
<input type="text" @ref="Input3" placeholder="Input 3" id="input3" />
...
<div>
    <button @onclick="() => Focus(1)">Element Focus 1</button>
    <button @onclick="() => Focus(2)">Element Focus 2</button>
    <button @onclick="() => Focus(3)">Element Focus 3</button>
</div>
...
<div>
    <button @onclick="() => FocusById(1)">Id Focus 1</button>
    <button @onclick="() => FocusById(2)">Id Focus 2</button>
    <button @onclick="() => FocusById(3)">Id Focus 3</button>
</div>
...

@code {

    [Inject] private IJSRuntime JS { get; set; }

    private ElementReference Input1;
    private ElementReference Input2;
    private ElementReference Input3;

    private async Task Focus(int number)
    {
        var input = number switch
        {
            1 => Input1,
            2 => Input2,
            _ => Input3
        };
        await JS.InvokeAsync<bool>("SetElementFocus", input);
    }

    private async Task FocusById(int number)
    {
        var input = number switch
        {
            1 => "input1",
            2 => "input2",
            _ => "input3"
        };
        await JS.InvokeAsync<bool>("SetFocusByElementId", input);
    }
}
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band