您的位置:首页 > 其它

重写RadioButtonList服务器控件的RenderItem方法,隐藏radio元素

2012-11-29 11:22 579 查看
思路:先判断浏览器是否为IE浏览器,如果是IE浏览器就将radio元素样式为width:0px;height:0px;若不是IE浏览器就将radio元素的样式设置为display:none。

//注释掉原来的RenderItem方法
//base.RenderItem(itemType, repeatIndex, repeatInfo, writer);
bool isIE = HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > 0;
ListItem li = Items[repeatIndex];
//回调函数的eventTarget
string name = this.ClientID.Replace('_','$')+"$"+repeatIndex.ToString();
//用于radio元素的name属性
string pname = this.ClientID.Replace('_','$');
//用于radio元素的id属性及label标签的for属性
string id = this.ClientID + "_" + repeatIndex.ToString();
//定义当AutoPostBack=true时的回调
string onclick = AutoPostBack?"onclick=\"javascript:setTimeout(\'__doPostBack(\\'"+name+"\\',\\'"+li.Value+"\\')\',0)\"":"";
//SelectedCssClass和ItemCssClass是我增加的两个Css,分别用于选中项的label和未选中项的label标签的class。
string css = li.Selected ? SelectedCssClass : ItemCssClass;
//可以在标签外围增加新标签,如<div style=''>{0}{1}</div>
string div = "{0}{1}";
//若为IE浏览器style=width:0px;height:0px; 其他浏览器style=display:none;
string radio = "<input type='radio' id='"+id+"' name='"+pname+"' value='"+li.Value+"'"+onclick+" style='"+(isIE?"width:0px;height:0px;":"display:none;")+"'/>";
string label = "<label for='"+id+"' class='"+css+"'>"+li.Text+"</label>";
writer.Write(string.Format(div,radio,label));


实测FF/IE浏览器效果相同



radio元素被隐藏,图中的按钮均为带css的label标签,当设置AutoPostBack=true时的回调也正常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: