为 PHP include() 中的元素设置类
我的所有页面顶部都有一个相同的水平菜单,我使用 PHP include() 语句添加该菜单。在我的样式表中,我想要一个类,如果用户位于特定页面上,则与该页面对应的菜单项将具有不同的颜色。所以,或多或少:
#menu { 背景颜色:蓝色; }
#menu .active { 背景颜色:绿色; 但是
,由于菜单来自 PHP include,所以它总是相同的。如何编写一些 PHP 或 JavaScript,将 class="active" 添加到每个页面的相应菜单项?
I have an identical horizontal menu at the top of all of my pages, which I add using a PHP include() statement. In my stylesheet I want to have a class where if the user is on a particular page, the menu item corresponding to that page will have a different color. So, more or less:
#menu {
background-color:blue;
}
#menu .active {
background-color:green;
}
But, since the menu comes from the PHP include, it's always the same. How can I write some PHP or JavaScript that adds class="active" to the appropriate menu item for each page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您
include()
一个文件时,被包含的文件可以访问它被包含的地方的所有范围内的变量。您可以轻松地设置一个变量来说明哪个菜单项应该处于活动状态。一个基本的例子可能是这样的:firstpage.php
menu.php
使用这种样式,您可以在包含之前简单地设置一个变量
$chosenMenu
您的菜单文件,您可以从那里控制它。When you
include()
a file, the included file has access to all the in-scope variables at the place where it gets included. You could easily set a variable to say which menu item should be active. A basic example might be something like this:firstpage.php
menu.php
With this style, you can simply set a variable
$chosenMenu
before including your menu file, and you can control it from there.