0

我最近创建了一个网站,其中有一个导航栏,它包含在使用 PHP 的页面中。

<?php include "Assets/Inclusions/NavigationBar.php" ?>

我希望活动页面列表项具有粗体文本,因此我使用 JavaScript 获取当前路径并使用大量 if 语句使相关元素变为粗体。

<script>
if(location.pathname == 'location.php')
document.getElementById("location").style.fontWeight="800";
    } ...and so on
</script>

有没有更好的方法我应该这样做?

4

2 回答 2

1

这似乎应该在服务器端完成。如果我犯了语法错误,请随时纠正这个问题,我写 PHP 已经有一段时间了,但这里是它的要点:

导航栏.php

<?php
    function isActive($page){
      $currentPage = $_GET['page']; // mypage.com?page='something'

      if ( !isset($currentPage) ) $currentPage = 'home';

      return $currentPage == $path;
    }
?>

<ul class="navigation">
  <li><a href="?page=home" 
          <?php if ( isActive('home') ) echo('class="active"'); ?> >Home</a></li>
  <li><a href="?page=About" 
          <?php if ( isActive('about') ) echo('class="active"'); ?>>About Us<a/></li>
</ul>

样式.css

a.active{
    font-weight: 800;
}
于 2014-07-01T16:18:28.243 回答
0

您可以使用 for 循环,获取导航中的所有链接元素,然后将路径与 href 进行比较。

var path = window.location.pathname;
var links = document.getElementsByClassName("navlink");
for(var i=0; i<links.length; i++){
   if(links[i].getAttribute("href")==path){
      links[i].style.fontWeight = "800";
      break;
   }
}

显然,您必须针对您的情况进行正确的比较,但这比编写一堆 if 更容易,并且更容易维护,因为您不必对要测试的位置进行硬编码。

如果你不担心与旧浏览器的兼容性,或者使用 jQuery,你可以使用属性选择器document.querySelector或 jQuery

//With querySelector
var link = document.querySelector("a[href='"+path+"']");
if(link!==null){
   link.style.fontWeight=="800";
}

//with jQuery
$("a[href='"+path+"']").css("font-weight","800");
于 2014-07-01T04:57:24.390 回答