无法更改当前 <nav> 的 css 类
Posted
技术标签:
【中文标题】无法更改当前 <nav> 的 css 类【英文标题】:Unable to change the css class of the current <nav> 【发布时间】:2020-10-08 20:47:39 【问题描述】:我的 asp.net MVC 核心 Web 应用程序中有以下 <nav>
:-
<nav>
<ul id="navigation">
<li class="@html.IsSelected(actions: "Home", controllers: "Default")"><a href="/">home</a></li>
<li class="@Html.IsSelected(actions: "FAQ", controllers: "Default")"><a href="/home/FAQ">FAQ</a></li>
<li class="@Html.IsSelected(actions: "Contact", controllers: "Default")"><a href="/home/contact/">Contact</a></li>
</ul>
</nav>
我想更改当前链接的类,我定义了以下 html 扩展方法:-
public static class HtmlHelperExtensions
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
但是当我点击任何<nav>
链接时,它们没有得到任何特殊效果!有什么建议吗?
谢谢
【问题讨论】:
【参考方案1】:调试以检查 IsSelected 方法是否返回了 cssClass。从您的代码中,当当前 url 是以下之一时,它只会返回 cssClass:
/默认/主页 /默认/FAQ /默认/联系方式此外,<li>
标签
好像没有内置的selected
cssClass,你需要在某个地方定义它。
我根据你的代码做了一个测试,只是改变了颜色:
_Layout.cshtml 中的<nav>
<nav>
<ul id="navigation">
<li style="@Html.IsSelected(actions: "Index", controllers: "Home")"><a href="/">Home</a></li>
<li style="@Html.IsSelected(actions: "FAQ", controllers: "Home")"><a href="/home/FAQ">FAQ</a></li>
<li style="@Html.IsSelected(actions: "Contact", controllers: "Home")"><a href="/home/contact/">Contact</a></li>
</ul>
</nav>
HTML 扩展:
public static class HtmlHelperExtensions
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "color:red")
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
结果:
【讨论】:
以上是关于无法更改当前 <nav> 的 css 类的主要内容,如果未能解决你的问题,请参考以下文章