自动调整文本区域大小以显示加载时的所有文本,而无需在 Blazor 中滚动
Resize text area automatically to show all text on load without scrolling in Blazor
我正在尝试自动调整文本区域的大小以显示加载时的所有文本,而无需在 Blazor 中滚动。
<textarea class="form-control" maxlength="255" style="width:250px;" @bind="Comment" id="Comments" required></textarea>
代码:
@code {
public string Comment = "This is test comments for textarea. This is test comments for textarea.";
}
以下css我用但没用...
textarea {
resize: vertical;
overflow: visible;
height:auto !important;
}
提前致谢。
如果您愿意使用 JSInterop,这将有效:
- 添加一个JS函数到_Host.cshtml:
...
<script>
ResizeTextArea = function (id) {
var el = document.getElementById(id);
if (el) {
el.style.height = "5px";
el.style.height = (el.scrollHeight + 5) + "px";
}
return true;
}
</script>
- 在您的 Blazor 组件中,注入
IJSRuntime
并添加 OnAfterRenderAsync
事件处理程序以调用 JS 函数:
@page "/interop"
@inject IJSRuntime jsRuntime
<h1>JSInterop</h1>
<textarea
class="form-control" maxlength="255" style="width:250px;"
@bind="Comment" id="Comments" required>
</textarea>
@code {
public string Comment = "This is test comments for textarea. This is test comments for textarea.";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await jsRuntime.InvokeAsync<bool>("ResizeTextArea", "Comments");
}
}
注:JS函数取自this SO answer
我正在尝试自动调整文本区域的大小以显示加载时的所有文本,而无需在 Blazor 中滚动。
<textarea class="form-control" maxlength="255" style="width:250px;" @bind="Comment" id="Comments" required></textarea>
代码:
@code {
public string Comment = "This is test comments for textarea. This is test comments for textarea.";
}
以下css我用但没用...
textarea {
resize: vertical;
overflow: visible;
height:auto !important;
}
提前致谢。
如果您愿意使用 JSInterop,这将有效:
- 添加一个JS函数到_Host.cshtml:
...
<script>
ResizeTextArea = function (id) {
var el = document.getElementById(id);
if (el) {
el.style.height = "5px";
el.style.height = (el.scrollHeight + 5) + "px";
}
return true;
}
</script>
- 在您的 Blazor 组件中,注入
IJSRuntime
并添加OnAfterRenderAsync
事件处理程序以调用 JS 函数:
@page "/interop"
@inject IJSRuntime jsRuntime
<h1>JSInterop</h1>
<textarea
class="form-control" maxlength="255" style="width:250px;"
@bind="Comment" id="Comments" required>
</textarea>
@code {
public string Comment = "This is test comments for textarea. This is test comments for textarea.";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await jsRuntime.InvokeAsync<bool>("ResizeTextArea", "Comments");
}
}
注:JS函数取自this SO answer