Blazor自动将文本区域滚动到底部



每次值更改时,如何将Blazor中的TextArea自动滚动到底部?

为了测试它,我尝试使用内联JS来更改我在Stack Overflow上找到的Element的大小:"oninput=";this.style.height="自动";this.style.height=(this.scrollHeight(+'px'"quot;

只要我手动填充TextArea,它就可以工作。但当从后端填充时,它不起作用,就像我想的那样:

protected async System.Threading.Tasks.Task TestButtonClick0()
{
TextAreaText += ">> SPAM Test n";
}

有几种方法可以自动滚动文本区域。然而,它可能无法使用内联JavaScript来完成,因为像";onchange";以及";oninput";由用户操作触发。因此,在以编程方式更新textarea值时,您需要调用一个JavaScript函数来执行此操作。最简单的方法是添加一个JavaScript函数,如:

function scrollToEnd(textarea) {
textarea.scrollTop = textarea.scrollHeight;
}

然后从Blazor页面调用:

@page "/"
@using Microsoft.JSInterop
@inject IJSRuntime JS
@functions{
ElementReference TextAreaRef;
string TextAreaText = "Example auto-scrolln";
void ScrollToEnd() {
JS.InvokeVoidAsync("scrollToEnd", new object[] {TextAreaRef});
}   
}
<button class="btn btn-primary m-2" @onclick="ScrollToEnd">Add Line</button>
<br/>
<textarea @ref=TextAreaRef value="@TextAreaText" class="form-control" rows="5"></textarea>

参见这个Blazor Fiddle的工作示例:

https://blazorfiddle.com/s/3ioprd8b

最新更新