自動適應輸入內容高度的TextBox控件(摘自羅永浩全集)
發表于:2007-06-30來源:作者:點擊數:
標簽:
關于Web 開發 上面UI布局的問題,我上次介紹了一個可以自動適應輸入內容寬度的TextBox控件,它可以解決在布局時預留控件大小和用戶數入內容多少上的矛盾。但是由于那個控件被限制了只能做為單行輸入使用:(,在輸入大塊文本時就力不從心了,那么就再做一個可自
關于Web
開發上面UI布局的問題,我上次介紹了一個可以自動適應輸入內容寬度的TextBox控件,它可以解決在布局時預留控件大小和用戶數入內容多少上的矛盾。但是由于那個控件被限制了只能做為單行輸入使用:(,在輸入大塊文本時就力不從心了,那么就再做一個可自動適應高度的TextBox。
原理和那個適應寬度的TextBox查不多,只是這個反而更加簡單,因為在高度方向上增長不會破壞頁面的整體布局效果(寬度上的如果在頁內會擠走別的元素的),所以就不需要使用Agent TextBox來作為實際錄入的容器了,直接把<TextArea>增高就行了。
響應onpropertychange事件,同步內容和<TextArea>的高度。當然如果完全根據內容增高可能也會因為內容太多而變得難看,就設置了一個最大高度限制屬性??丶Ч缦拢?
最大高度為200px的AutoTextBox Demo:
最大高度為200px但初始高度為3rows的AutoTextBox Demo:
高度增長無限制的AutoTextBox Demo:
如果控件的MaxHeight屬性小于或等于0,那么增長高度無限制。
附 AutoTextBox 控件源碼#region 附 AutoTextBox 控件源碼
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace WebExcel.UI.WebControls
{
/**//// <summary>
/// Summary description for AutoLengthTextBox.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:AutoTextArea runat=server></{0}:AutoTextArea>")]
public class AutoTextArea : System.Web.UI.WebControls.TextBox
{
[DefaultValue(200)]
public int MaxHeight
{
get
{
object obj = ViewState["MaxHeight"];
return obj == null ? 200 : (int)obj;
}
set
{
ViewState["MaxHeight"] = value;
}
}
[DefaultValue(60)]
public int MinHeight
{
get
{
object obj = ViewState["MinHeight"];
return obj == null ? 60 : (int)obj;
}
set
{
ViewState["MinHeight"] = value;
}
}
protected override void OnPreRender(EventArgs e)
{
this.Attributes["minHeight"] = this.MinHeight.ToString();
if ( this.Height == Unit.Empty )
{
this.Height = this.MinHeight;
}
else
{
this.Height = (int)Math.Max(this.MinHeight, this.Height.Value);
}
base.OnPreRender (e);
}
/**//// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)
{
string strCode;
if ( this.MaxHeight <= 0 )
{
strCode = "this.style.height=Math.max(this.minHeight,this.scrollHeight)+(this.offsetHeight-this.clientHeight)";
}
else
{
strCode = "this.style.height=(this.scrollHeight>200)?200:Math.max(this.minHeight,this.scrollHeight)+(this.offsetHeight-this.clientHeight)";
}
base.Attributes["onpropertychange"] = strCode;
// base.Attributes["onfocus"] = "this.height=this.height";
if ( base.Rows == 0 )
{
base.Rows = 1;
}
base.TextMode = TextBoxMode.MultiLine;
base.Render(output);
}
}
}
#endregion
原文轉自:http://www.kjueaiud.com