如何在header.php中使用交互式菜单栏? [英] How to use an interactive menu bar in a header.php?

查看:57
本文介绍了如何在header.php中使用交互式菜单栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢将我的徽标和菜单栏保存在header.php中,这样更新它就不那么痛苦了。但是我只是在我的菜单栏中添加了交互性,并且我必须将每个页面添加到css类中。



我的主页菜单代码:

I like to keep my logo and menu bar in a header.php so that way its not such a pain to update it. However I just added interactivity to my menu bar and for each page I have to add active to the css class.

My menu code for the home page:

<ul> 
<li><a class="menubar active" href="index.php">Home</a></li> 
<li><a class="menubar" href="scores.php">Scores</a></li> 
<li><a class="menubar" href="players.php">Our Eagles</a></li> 
<li><a class="menubar" href="schedule.php">Game Schedule</a></li> 
</ul>





我的尝试:



我什么都没试过,但是,因为我甚至不知道这是否可行。



What I have tried:

I have tried nothing, yet, because I don't even know if this is possible.

推荐答案

当然,它是可能。

首先,从主菜单中删除活动类。

您需要编写javascript代码才能完成此操作。加载页面时,代码将找到与当前页面URL匹配的菜单栏链接,并将活动类添加到其中。

参考
如何根据URL将活动类添加到导航菜单 [ ^ ]。

考虑在哪里放置css和javascript代码,以便它们只写入一次我只是在header.php中添加了javascript代码。

Of course, it's possible.
First thing first, remove the 'active' class from the Home menu.
You will need to write javascript code to accomplish this. When a page is loaded, the code will find the menubar link that matches the current page url and add the active class to it.
Take reference from
How to Add Active Class to a Navigation Menu Based on URL[^].
Consider where to put the css and javascript code so that they are only written once and simply be included in every page.
As an example, I have added the javascript code in the header.php.
<ul> 
<li><a class="menubar" href="index.php">Home</a></li> 
<li><a class="menubar" href="scores.php">Scores</a></li> 
</ul>
<script>
function addClass(){
  //Get the current page url	
  var pageurl = window.location.href;
  //Find all the anchor links with class name 'menubar'
  var menubar = document.getElementsByClassName('menubar');
  //Loop thru them to find the matching anchor link
  for(i=0;i<menubar.length;i++) { 
    //When the matching anchor link found
    if(menubar[i].href.toLowerCase()==pageurl.toLowerCase())    {
	  //Add 'active' to the existing class of the found anchor link
      menubar[i].className +=' active';
    }
  }
}
window.onload(addClass());
</script>


这篇关于如何在header.php中使用交互式菜单栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆