gpt4 book ai didi

javascript - 自动调整文本区域大小以显示加载时的所有文本,而无需在 Blazor 中滚动

转载 作者:行者123 更新时间:2023-11-28 10:07:41 25 4
gpt4 key购买 nike

我正在尝试自动调整文本区域的大小以显示加载时的所有文本,而无需在 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,这将有效:

  1. 向 _Host.cshtml 添加一个 JS 函数:
...

<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>
  1. 在您的 Blazor 组件中,注入(inject) 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

关于javascript - 自动调整文本区域大小以显示加载时的所有文本,而无需在 Blazor 中滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59310058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com