首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 自訂 TextBox 控件:內建輸入提示(Watermark)功能

     編輯:關於ASP.NET

功能描述

擴充 TextBox,新增 Tip 屬性。控件取得焦點時若值等於提示文字則清空並恢復黑色字體;失去焦點且值為空時顯示灰色提示文字。使用者輸入提示文字作為實際內容時,Text 屬性回傳空字串。

關鍵程式碼

public string Tip { get; set; }

public override string Text {
    get { return base.Text.ToLower() == Tip.ToLower() ? string.Empty : base.Text; }
    set { base.Text = value; }
}

protected override void Render(HtmlTextWriter writer) {
    this.Attributes.Add("tip", Tip);
    this.Attributes.Add("onblur", "if(this.value==''){this.style.color='#C1C1C1';this.value='" + Tip + "';};");
    this.Attributes.Add("onfocus", "if(this.value=='" + Tip + "'){this.style.color='#000000';this.value='';};");
    if (string.IsNullOrEmpty(base.Text.Trim())) {
        this.Attributes.Add("value", this.Tip);
        this.Attributes.Add("style", "color:#C1C1C1");
    }
    base.Render(writer);
}

編譯後即可在工具箱拖放使用,屬性視窗可直接設定 Tip 文字。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved