Ruby on Rails 在导航栏上突出显示当前链接?
谁能告诉我如何使用 css 突出显示(用颜色)导航栏上的当前链接?我不想使用控制器选项。 这是来自shared/menu.html.erb的代码:
<div id = "navigation">
<ul>
<li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li>
<li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li>
</ul>
</div>
Can anyone tell me how to highlight (with color) the current link on a navigation bar, using css? I don't want to use the controller option.
Here is the code from shared/menu.html.erb:
<div id = "navigation">
<ul>
<li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li>
<li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li>
</ul>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一种方法是处理当前的 controller_name 和 action_name 来检测您所在的页面。这很好,但它为客户端特定的模板添加了一些服务器端内容。 Rails 助手使用的方式是 link_to_unless_current。 JS 的最小使用量。请参阅此处的示例
第二个是解析$(location) 并直接将某个类添加到选定的导航项中以突出显示它。
第三种(取决于对象)是使用实体的当前状态构建一个 JS 对象,并添加方法以将类添加到活动导航中。然后您可以实例化这个 JS 类,传递对象并保持逻辑封装。
The first approach is to handle current controller_name and action_name to detect what page you are on. It's good, but it adds a bit of server-side to client-specific template. The rails helper uses that way is link_to_unless_current. Minimum usage of JS. See an example here
The second is to parse $(location) and directly add a certain class to the selected navigation item to highlight it.
The third (depends on an object) is to build a JS object with current state of entity and add methods to add a class to an active nav. Then you can instantiate this JS class, passing on the object and keeping the logic encapsulated.
像这样的东西对你有用。当然,您必须根据您的目的对其进行调整,也许使匹配变得更加复杂(目前这只会匹配路径,正如您在示例中所做的那样)。
更好的是,您可以在某处定义一个“当前”类,然后只需添加它:
Something like this would work for you. Of course you'd have to tweak it to your purposes, maybe get more sophisticated with the match (currently this would only match paths, as you have in your example).
Better still, you'd define a "current" class somewhere, then simply add it:
有几种方法可以解决这个问题,
但如果你追求的是简单的,
我建议在你的身体中添加一个类。
然后在你的 css 中你可以执行以下操作。
如果您想要拆分多个页面,这可能会变得复杂,
但对于这个基本的例子来说应该没问题。
There are a few approaches to this,
but if you're after a simple one,
I suggest adding a class to your body.
Then in your css you can do the following.
This can get complicated if you have multiple pages you want to split,
but for this basic example it should be ok.
使用 Rails Helper:link_to_unless_current
简单且最快。
我喜欢@Anatoly的想法,使用link_to_unless_current 帮助者,所以我提出了以下解决方案。复制并粘贴以节省您一些时间。:
它有什么作用?
希望这有帮助。
Use a Rails Helper: link_to_unless_current
Simple and the fastest.
I like @Anatoly's idea to use the link_to_unless_current helper so I whipped up the following solution. Copy and paste to save you some time.:
What does it do?
Hope this helps.