问题
If you set a CSS class on a TextBox control with the CssClass property, targeting that TextBox with the TextBoxWatermarkExtender that has a WatermarkCssClass property will cause it to lose its CSS class, i.e., it is reseting the class attribute to the watermark text, rather than adding it as an additional class:
<asp:TextBox ID="TextBox1" runat="server" CssClass="text" />
<ajax:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID="TextBox1" WatermarkCssClass="watermark" />
as an output
<input type="text" class="text" />
becomes
<input type="text" class="watermark" />
when the watermark style is in effect rather than
<input type="text" class="text watermark" />
Can anyone suggest the workaround?
Please do not suggest below the workaround because I have a requirement to add TextBox CssClass run time. I have added TextBox CssClass by javascript but still TextBoxWatermarkExtender WatermarkCssClass overwrites the textbox classes.
Set the WatermarkCssClass property to include both classes:
<asp:TextBox ID="TextBox1" runat="server" CssClass="text" />
<ajax:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID="TextBox1" WatermarkCssClass="text watermark" />
回答1:
I looked into the JS that is emitted by the asp.net ajax and here's how the WaterMarkExtender is created.
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.TextBoxWatermarkBehavior, {"ClientStateFieldID":"TextBoxWatermarkExtender1_ClientState","WatermarkCssClass":"watermark","WatermarkText":"Hello","id":"TextBoxWatermarkExtender1"}, null, null, $get("TextBox1"));
})
So I think you can modify the class of the tb after application init event.
<script type="text/javascript">
Sys.Application.add_load(appl_load); //register load handler
//load handler
function appl_load() {
$("#TextBox1").addClass("text");
}
</script>
Ref: ASP.NET Ajax life cycle
Generic... may be you can try finding the input using ".class" or "input". It depends on overall UI because you mentioned in your question that you add CssClass to the Textbox at runtime. One other way I can think of is doing the reverse i.e. get all the inputs that has watermark class and then add the text class.
<script type="text/javascript">
Sys.Application.add_load(appl_load); //register load handler
//load handler
function appl_load() {
$(".watermark").addClass("text");
}
</script>
来源:https://stackoverflow.com/questions/21755995/textboxwatermarkextender-watermarkcssclass-overwrites-textbox-cssclass