1

我在 asp.net 中动态生成文本框并在其上设置默认文本。现在,我想在文本框第一次成为焦点时清除它,但如果用户不输入任何内容,请再次显示默认文本。

 protected void btnAdd_Click(object sender, EventArgs e)
{
    TextBox textName;
    textName = new TextBox();
    textName.Text = "mail";
    TextBox textName2;
    textName2 = new TextBox();
    textName2.Text = "tel";
    string divContect = ControlRenderer(divTextBox);
    divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "&nbsp;&nbsp" + ControlRenderer(textName2) + "<br/><br/>";

}

public string ControlRenderer(Control control)
{
    StringWriter writer = new StringWriter();
    control.RenderControl(new HtmlTextWriter(writer));
    return writer.ToString();
}  
4

2 回答 2

0

您可以将 Javascript 与 onblur 和 onfocus 事件一起使用。

希望这会帮助你。

请试试这个:

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox textName;
        textName = new TextBox();
        textName.ID = "textName";
        textName.Text = "mail";
        textName.ForeColor = System.Drawing.Color.Gray;
        SetPromptText(textName);

        TextBox textName2;
        textName2 = new TextBox();
        textName2.ID = "textName2";
        textName2.Text = "tel";
        textName2.ForeColor = System.Drawing.Color.Gray;
        SetPromptText(textName2);

        string divContect = ControlRenderer(divTextBox);
        divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "&nbsp;&nbsp" + ControlRenderer(textName2);
    }

    public string ControlRenderer(Control control)
    {
        StringWriter writer = new StringWriter();
        control.RenderControl(new HtmlTextWriter(writer));
        return writer.ToString();
    }

    private void SetPromptText(TextBox textBox)
    {
        string onFocusAction = "if (this.value == \"{0}\") {{ this.value = \"\"; this.style.color = \"black\"; }} ";
        string onBlurAction = " if (this.value == \"\") {{ this.value = \"{0}\"; this.style.color = \"gray\"; }} else this.style.color = \"black\";";
        onBlurAction = string.Format(onBlurAction, textBox.Text);
        onFocusAction = string.Format(onFocusAction, textBox.Text);
        textBox.Attributes["onblur"] = onBlurAction;
        textBox.Attributes["onfocus"] = onFocusAction;
    }
于 2013-05-28T13:46:47.037 回答
0
private void OnTestTextBoxGotFocus(object sender, RoutedEventArgs e)
{  
if (testTextBox.Text.Equals("Type here...", StringComparison.OrdinalIgnoreCase))
    {
        testTextBox.Text = string.Empty;
    }  
}
private void OnTestTextBoxLostFocus(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(testTextBox.Text))
    {
        testTextBox.Text = "Type here...";
    }
}
于 2013-05-28T13:15:19.013 回答