簡體   English   中英

如何使文本框(多行)的大小適應 ASP .NET C# 中的文本?

[英]How to adapt the size of a Textbox (MultiLine) to a text in ASP .NET C#?

我有一個 .aspx 表單,並且在Page_Load事件中,我為數據庫中的控件(文本框、下拉列表等)分配了幾個值,但是我有一個文本框控件,其中文本可能非常大或非常小,它在這里我想知道是否可以使文本框大小動態化。

當窗體完成加載文本框控件時,它會顯示如下:。

在此處輸入圖像描述

但我想像這樣想象它(一切都取決於文本):

在此處輸入圖像描述

文本框代碼:

<asp:TextBox runat="server" ID="txt" TextMode="MultiLine" Height="80px" ReadOnly="true" CssClass="form-control"></asp:TextBox> 

我正在使用 .NET 框架 4.5.2,我不確定是否應該使用 jQuery 中的任何功能,如果可以,該怎么做?

當文本很大或很小時更改 TextBox 高度,因此當您從數據庫中獲取值時更改高度,例如當文本很大時 Height="400px" 和當 textn 很小時 Height="200px"

您可以在頁面加載時使用 Javascript 或 Jquery 輕松完成此操作。

Jquery:

$(function(){//executes when dom is ready

    var textAreaAdjust = function(control) {//function to set the height
        $(control).height(1);
        $(control).height($(control).prop('scrollHeight'));
    }

    textAreaAdjust($('#txt'));// call the function passing the textarea control in
});

Javascript:

document.addEventListener("DOMContentLoaded", function () {

        var textAreaAdjust = function(control){//funciton to measure and set height
            control.style.height = "1px";
            control.style.height = (25+control.scrollHeight)+"px";
        };

        var textControl = document.getElementById("txt");//get the textarea
        textAreaAdjust(textControl);//pass it into the function

}​);

歸功於這個答案

您可以使用文字控件

<asp:Literal ID="Literal1" runat="server"></asp:Literal> 

或添加了runat="server"的 html div。

<div id="specialDiv" runat="server"></div>

c#

specialDiv.InnerText = "asdfasdf...etc";

請注意,如果您使用CssClass="form-control" ,您可能必須通過將height設置為auto而不是預設/硬編碼高度來更新 css。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM