问题描述
我生成绑定到将XmlDataSource Repeater控件的菜单。
I'm generating a menu with a Repeater control bound to an XmlDataSource.
<asp:Repeater ID="myRepeater" runat="server"
DataSourceID="myDataSource"
onitemdatabound="myRepeater_ItemDataBound"
onitemcreated="myRepeater_ItemCreated">
<HeaderTemplate>
<ul class="menu_list">
</HeaderTemplate>
<ItemTemplate>
<li id="liMenu" runat="server"><asp:HyperLink ID="hrefMenuItem" runat="server" Text='<%# XPath("@text")%>' NavigateUrl='<%# XPath("@href")%>'></asp:HyperLink></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
<asp:XmlDataSource runat="server" ID ="myDataSource" XPath="Menu/Items/*" EnableCaching="False" />
我希望能够根据鼠标悬停事件和当前选择的菜单项来设置含Li的风格。我通过HtmlGenericControl试过,但我收到一个错误,它是只读的。
I'd like to be able to set the style of the containing LI based on mouseover events and currently selected menu item. I tried via the HtmlGenericControl, but I receive an error that it's readonly.
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hrefCurrentMenuLink = e.Item.FindControl("hrefMenuItem") as HyperLink;
HtmlGenericControl l_genericControl = e.Item.FindControl("liMenu") as HtmlGenericControl;
if ((hrefCurrentMenuLink != null) && (l_genericControl != null))
{
string l_currentPage = GetCurrentWebPage();
if (String.Compare(Path.GetFileNameWithoutExtension(hrefCurrentMenuLink.NavigateUrl), l_currentPage, StringComparison.OrdinalIgnoreCase) == 0)
l_genericControl.Style = "on-nav";
else
l_genericControl.Style = "off-nav";
l_genericControl.Attributes.Add("onmouseover", "navOn(this)");
l_genericControl.Attributes.Add("onmouseout", "navOff(this)");
}
}
}
有没有办法做到这一点?
Is there any way to accomplish this?
推荐答案
的样式属性是一个集合。做到这一点:
The style property is a collection. Do this:
l_genericControl.Style.Add("css-name", "css-value")
或者,如果你正在使用的CSS类,然后更改CssClass属性:
Or if you are using CSS classes, then change the CssClass property:
l_genericControl.CssClass = "on-nav";
如果你想切换与您的JavaScript的CSS类,尝试这样的事情(未经测试):
If you're trying to toggle the CSS class with your javascript, try something like this (untested):
l_genericControl.Attributes.Add("onmouseover", "this.className='on-nav';");
l_genericControl.Attributes.Add("onmouseout", "this.className='off-nav';");
如果你想改变风格,你的JavaScript,这可能工作:
If you want to change the style with your javascript, this might work:
l_genericControl.Attributes.Add("onmouseover", "this.style.color='red'; this.style.backgroundColor='yellow';");
l_genericControl.Attributes.Add("onmouseout", "this.style.color='black'; this.style.backgroundColor='none';");
这篇关于ASP.NET:编程方式设置一个HTML元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!