keeping highlighted tab in navigation bars

纵然是瞬间 提交于 2019-12-11 13:44:50

问题


thanks for your time. I've been having a lot of trouble trying to highlighting the "active" tab on a navbar i am using. I'm trying to do this through CSS but the problem arises when I change pages. I will add the following code:
function updateMenu(num)
{

var menuCode =

'<ul id="menu">' +
'<li><a href="software/menu.php" onclick="updateMenu(1);"';
if(num == 1){menuCode +=' class="current"';}
menuCode += '>Software</a></li>'+
'<li><a href="users/menu.php" onclick="updateMenu(2);"';
if(num == 2){menuCode +=' class="current"';}
menuCode += '>Software</a></li>';

document.getElementById("cssMenu").innerHTML = menuCode;
}

And my list goes as follows:

<ul id="menu">

<li><a href="software/menu.php" onclick="updateMenu(1);">Software</a></li> <li><a href="user/menu.php" onclick="updateMenu(2);">Users</a></li> </ul>

I feel it's an unelegant solution because of all the code wrote in the updateMenu function and i was wondering if there was a more elegant solution to my problem. (You can see it's on moving the "class=current" so the CSS works properly).


回答1:


I'm not sure what your exact requirement is. Assuming that on clicking the tab, it does NOT go to another page, the following code will help [please use Jquery]:

HTML :

<ul id="menu">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

Javascript :

<script>
 $(document).ready(function(){
  $("#menu li").click(function(){
    $("#menu li").removeClass("highlight");
    $(this).addClass("highlight");
 });
});
</script>

CSS :

.highlight {
 background: #f00;
}


来源:https://stackoverflow.com/questions/10354983/keeping-highlighted-tab-in-navigation-bars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!