简体   繁体   English

如何在PHP包括的页面中包含的HTML标记上设置CSS类

[英]How To Set CSS Classes On HTML Tags Which Are Included In The Page With PHP Include's

I'm building a website which uses a lot of repeated styles and HTML tags, such as the header, the navigation bar at the top, and the footer at the very bottom. 我正在构建一个使用大量重复样式和HTML标记的网站,例如标题,顶部的导航栏和最底部的页脚。 Instead of typing all of that repeated code in again and again, I'd like to use PHP include statements to include everything that I need. 我不想一次又一次地输入所有重复的代码,而是想使用PHP include语句来包含我需要的所有内容。

While that's all well and good, this poses a problem with my navigation bar. 虽然这一切都很好,但这对我的导航栏造成了问题。 I use a CSS class attached to the navigation link to let the user know what page they're on (using a different background color). 我使用附加到导航链接的CSS类让用户知道他们所在的页面(使用不同的背景颜色)。 On each page, I manually specify which link gets that special class. 在每个页面上,我手动指定哪个链接获取该特殊类。 If I were to simply include that content via a PHP include statement, I couldn't manually specify the class. 如果我只是通过PHP include语句包含该内容,我无法手动指定该类。

My question is: how would I be able to do that? 我的问题是:我怎么能这样做? Either by using a separate PHP script to find out which page the user is on, and then specify the class to style the link appropriately, or by using JavaScript to do the same thing? 通过使用单独的PHP脚本来找出用户所在的页面,然后指定类来适当地设置链接样式,或者使用JavaScript来执行相同的操作? Or maybe there's something else that I'm missing? 或者也许还有其他一些我不知道的东西? Who knows! 谁知道! And as such, I ask! 就这样,我问!

An easy way to do it would be to add a PHP variable like $page before the include and then use this variable in your included menu file to determine which menu item needs highlighting. 一个简单的方法是在include之前添加一个PHP变量(如$page ,然后在包含的菜单文件中使用此变量来确定哪个菜单项需要突出显示。

So in the file with the includes: 所以在包含的文件中:

$page = "home";
include("menu.php");

And in the menu file: 并在菜单文件中:

<ul>
    <li <?php if( $page == "home") echo 'class="active"' ?> >home</li>
    <li <?php if( $page == "about") echo 'class="active"' ?> >about</li>
    <li <?php if( $page == "contact") echo 'class="active"' ?> >contact</li>
</ul>

The example above isn't the tidiest or most optimal solution, but it gives you an idea of how you could achieve what you are trying to do by using PHP variables. 上面的示例不是最整洁或最优的解决方案,但它让您了解如何通过使用PHP变量来实现您尝试执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM