我对 php 还比较陌生,所以我不能说这是最佳实践还是 hack,但它确实有效。
我知道这是一个老话题,但我有一个解决方案可以解决 Frederik 在 Chris Sobolewski 的帖子中提出的问题。
我们假设您有一个页眉(包含链接)和页脚模板,并且不希望为每个页面创建新的页眉。
由于每个链接都将我们带到具有唯一页面名称的新页面,因此我们可以使用它为每个链接提供一个 id。或者,我们可以使用 $_GET 中的参数,具体取决于您的导航设置。
在您的示例中,我们可以使用如下内容:
<nav>
<ul>
<li class="selected"><a href="index.php" id="indexLink">Home</a></li>
<li ><a href="biography.php" id="biographyLink">Biography</a></li>
<li ><a href="photo.php" id="photoLink">Photo</a></li>
<li ><a href="work.php" id="workLink">Work</a></li>
<li ><a href="contact.php" id="contactLink">Contact</a></li>
</ul>
<div class="clear"></div>
</nav>
现在在我们的 php 文件中,我们可以使用我们喜欢的任何技术来操作 DOM,从当前活动的链接中添加和删除活动类。
请记住,我是新手,如果这不是操作 DOM 的最佳实践,请原谅我,但这就是我的处理方式:
?php
function curPageName() {
$pageName = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return trim($pageName, ".php");
}
//string to find the active class
$classString=' class="activeLink"';
//String to find the current page link
$pageString='id="'.curPageName().'Link"';
//String to set the current page link active
$activeString='id="'.curPageName().'Link" class="activeLink"';
//load the html from the header file
$fileContents=file_get_contents("header.html");
//Remove the old active class
$newHtmlContent=str_replace($classString, "", $fileContents);
//Set the new active class
$newHtmlContent=str_replace($pageString, $activeString, $newHtmlContent);
//Save the manipulated HTML
file_put_contents("header.html",$newHtmlContent);
?>
然后在你的 CSS 中简单地设置你想要的 activeLink 样式。
我很想简单地搜索 URL 来修改头文件的 DOM,但是如果在文档中的其他地方有任何其他指向同一页面的链接,我们不希望它们也被样式化。所以我想最好添加一个ID。如果我们在 php 中使用其他一些操作 DOM 的方法,这也会更好。
任何关于解决方案是好的还是坏的做法的反馈也很感激!