想要的效果是让当前选中的控件有一个高亮的效果.
![](http://link-to.cn/image.axd?picture=activeControl.jpg)
要实现这个功能要先有一个给控件添一个
Attributes 的方法.
#region
SetInputControlsHighlight
/// <summary>
/// 设置当控件得到焦点的时候,控件的样式.
/// </summary>
/// <param name="container"> 指定的控件. </param>
/// <param name="className"> 应用样式的样式名称 </param>
/// <param name="onlyTextBoxes"> 是否只允许TextBox有这个属性. </param>
public static void SetInputControlsHighlight(Control container,
string className, bool onlyTextBoxes)
{
foreach (Control ctl in container.Controls)
{
// 在if里面可以加想要的控件.
if ((onlyTextBoxes && ctl is TextBox) || ctl is TextBox ||
ctl is DropDownList || ctl is ListBox || ctl is CheckBox ||
ctl is RadioButton || ctl is RadioButtonList || ctl is CheckBoxList)
{
WebControl wctl = ctl as WebControl;
wctl.Attributes.Add( " onfocus " , string .Format(
" this.className = '{0}'; " , className));
wctl.Attributes.Add( " onblur " , " this.className = ''; " );
}
else
{
if (ctl.Controls.Count > 0 )
SetInputControlsHighlight(ctl, className, onlyTextBoxes);
}
}
}
#endregion
/// <summary>
/// 设置当控件得到焦点的时候,控件的样式.
/// </summary>
/// <param name="container"> 指定的控件. </param>
/// <param name="className"> 应用样式的样式名称 </param>
/// <param name="onlyTextBoxes"> 是否只允许TextBox有这个属性. </param>
public static void SetInputControlsHighlight(Control container,
string className, bool onlyTextBoxes)
{
foreach (Control ctl in container.Controls)
{
// 在if里面可以加想要的控件.
if ((onlyTextBoxes && ctl is TextBox) || ctl is TextBox ||
ctl is DropDownList || ctl is ListBox || ctl is CheckBox ||
ctl is RadioButton || ctl is RadioButtonList || ctl is CheckBoxList)
{
WebControl wctl = ctl as WebControl;
wctl.Attributes.Add( " onfocus " , string .Format(
" this.className = '{0}'; " , className));
wctl.Attributes.Add( " onblur " , " this.className = ''; " );
}
else
{
if (ctl.Controls.Count > 0 )
SetInputControlsHighlight(ctl, className, onlyTextBoxes);
}
}
}
#endregion
为了要个控件添加这个属性.要重写Onload();
protected
override
void
OnLoad(EventArgs e)
{
// add onfocus and onblur javascripts to all input controls on the forum,
// so that the active control has a difference appearance
// 设置当前空间的样式.
Helpers.SetInputControlsHighlight( this , " highlight " , false );
base .OnLoad(e);
}
{
// add onfocus and onblur javascripts to all input controls on the forum,
// so that the active control has a difference appearance
// 设置当前空间的样式.
Helpers.SetInputControlsHighlight( this , " highlight " , false );
base .OnLoad(e);
}
别忘了还要有一个样式单:
/*
**********************************************
/ 设置当前选中控件的样式.
/********************************************** */
.highlight
{
background-color : #fefbd2 ;
color : #000080 ;
}
/ 设置当前选中控件的样式.
/********************************************** */
.highlight
{
background-color : #fefbd2 ;
color : #000080 ;
}
文章来源: http://link-to.cn/post/2007/12/activeControlHighlight.aspx