活动菜单高亮CSS

33

我想要突出显示您点击的当前菜单。我正在使用CSS,但它没有起作用。

以下是我的CSS代码:

#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }

这是我的HTML代码:

<div id="sub-header">
    <ul>
        <li> <a href="index.php">Home</a> </li>
        <li> <a href="contact.php">Contact Us</a> </li>
        <li> <a href="about.php">About Us</a> </li>
    </ul>
</div>

当我悬停并且菜单处于活动状态时,这就是我喜欢的。

当我悬停并且菜单处于活动状态时,这就是我喜欢的

悬停是可以的,问题在于当我点击菜单后,黑色背景不会显示。


@Jonathan,我已经解决了,而且比你给出的方法还要简单。

这是我的答案:

$(function(){
    // this will get the full URL at the address bar
    var url = window.location.href; 

    // passes on every "a" tag 
    $("#sub-header a").each(function() {
            // checks if its the same on the address bar
        if(url == (this.href)) { 
            $(this).closest("li").addClass("active");
        }
    });
});

然后在我的CSS文件中:

.active { background-color: #000; }
/* to override the existing css for "a" tag */
#sub-header .active a{ color: #fff; }
11个回答

37
在每个页面的标签中添加一个类:
<body class="home">

或者如果您正在联系页面上:

<body class="contact">

当您创建样式时,请考虑以下内容:

#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}

#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }

最后,将类名称应用于您的列表项:

<ul>
  <li class="home"><a href="index.php">Home</a></li>
  <li class="contact"><a href="contact.php">Contact Us</a></li>
  <li class="about"><a href="about.php">About Us</a></li>
</ul>

当你位于 body.home 页面时,li.home a 链接将拥有默认的样式,表明它是当前页面。


@justin JavaScript可能会有点冗长,但我相信用jQuery解决方案只需要几行代码就可以完成。 - Sampson
2
@justin 请记住,jQuery解决方案仅在用户启用JavaScript时才有效。 - Sampson
值得注意的是,如果您的导航菜单中没有太多页面,那么这个解决方案才是实用的。例如,如果您有一个包含数百个页面的注册表,这将很快变得混乱。 - Dennis
能否将类放在<div>中而不是<body>标签中? - kaynewilder
最好使用 aria-page=current 属性而不是类。这是因为 CSS 类不能告诉浏览器哪个页面是活动的。这种解决方案有利于使用辅助技术的人,例如使用屏幕阅读器的低视力人群。很多人通过 Stack Overflow 学习编码,如果我们在这些示例中使用最佳实践,网络将变得更加无障碍。 - Pepijn Gieles
显示剩余6条评论

2

简易添加方式

<div id='cssmenu'>
<ul>
<li class=''><a href='1.html'><span>1</span></a></li>
<li class=''><a href='2.html'><span>2</span></a></li>
<li class='' style="float:right;"><a href='3.html'><span>3</span></a></li>
</ul>
</div>

$("document").ready(function(){
$(function() {
$('.cssmenu a[href="' + location.pathname.split("/")[location.pathname.split("/").length-1] + '"]').parent().addClass('active');
});

});

2

鉴于这个问题的标签是,我将提供我完成它的方法。

  1. 在.css文件中创建一个类。

    a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

  2. 导航栏将如下所示:

    • 首页
    • 联系我们
    • 关于我们

注意: 如果您已经使用一个类为所有导航栏元素设置样式,您可以在html标记中与我们创建的特殊情况类级联通用类之后使用 white-space

例子: 这里,我已经从一个名为'navList'的类中导入了我的样式,该类是为所有列表项创建的。但特殊情况的样式属性属于类'activePage'

CSS文件:

a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}

HTML文件:

<div id="sub-header">
    <ul>
        <li> <a href="index.php" class= "navList activePage" >Home</a> </li>
        <li> <a href="contact.php" class= "navList">Contact Us</a> </li>
        <li> <a href="about.php" class= "navList">About Us</a> </li>
    </ul>
</div>

看我是如何将一个类名级联到另一个后面的。


2

仅提供链接的答案在SO上不被视为有价值的。请在这里提供解决方案。 - isherwood

1

假设我们有这样一个菜单:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

假设我们当前的URL为https://demosite.com/link1.html

使用以下函数,我们可以将活动类添加到菜单中的href与我们的URL相同的项。

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(p => {
  if(currentURL.indexOf(p.getAttribute("href")) !== -1){
    p.classList.add("active");
  }
})

1
也许这是一种非常不好的方式,只适用于懒人,但我决定说出来。
我使用了PHP、Bootstrap和Font Awesome。
简单来说,我有两个页面:1.首页和2.创建用户。
将此代码放在您的代码之上。
<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
    case "create-user":
        $a = 2;
        break;
    case "index":
        $a = 1;
        break;
    default:
        $a=1;
}
?>

在菜单中,您需要在menu1的class中添加<?php if($a==1){echo "active";} ?>,对于menu2,您需要添加<?php if($a==2){echo "active";} ?>。请保留HTML标签。
<ul id="menu" class="navbar-nav  flex-column text-right mt-3 p-1">
                        <li class="nav-item mb-2">
                            <a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
                                        class="fas fa-home fa-lg text-light ml-3"></i>dashbord</a>
                        </li>
                        <li class="nav-item mb-2">
                            <a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
                               class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
                                <i class="fas fa-user fa-lg text-light ml-3"></i>manage users
                                <span class="float-left"><i class="fas fa-angle-down"></i></span>
                            </a>

                            <ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
                                <li class="nav-item mb-2">
                                    <a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
                                </li>

                                <li class="nav-item mb-2">
                                    <a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
                                </li>

                            </ul>
                        </li>

                    </ul>

并添加CSS样式

.customlihamid {
    transition: all .4s;
}

.customlihamid:hover {
    background-color: #8a8a8a;
    border-radius: 5px;
    color: #00cc99;
}
.nav-item > .nav-link.active  {
    background-color: #00cc99;
    border-radius: 7px;
    box-shadow: 5px 7px 10px #111;
    transition: all .3s;
}
.nav-item > .nav-link.active:hover  {
    background-color: #8eccc1;
    border-radius: 7px;
    box-shadow: 5px 7px 20px #111;
    transform: translateY(-1px);
}

and in js add

$(document).ready(function () {
   $('.navbar-nav .nav-link').click(function(){
      $('.navbar-nav .nav-link').removeClass('active');
      $(this).addClass('active');
   })
});

首先在没有 JavaScript 代码的情况下检查您的工作,以了解 JavaScript 代码的用途。


0

使用简单的两行监听器的另一种变体

$( ".menu_button" ).click(function() {

    $( ".menu_button" ).removeClass('menu_button_highlight');
    $(this).addClass('menu_button_highlight');
});

=====

    <a class='menu_button' href='#admin'>Admin</a>
    <br/>

    <a class='menu_button' href='#user_manager'>User Manager</a>
    <br/>

    <a class='menu_button' href='#invite_codes'>Invite Codes</a>

====

.menu_button {

    padding: 0 5px;
}

.menu_button_highlight {

    background: #ffe94c;
}

0

试试这个(复制并粘贴):

Test.html:-

<html>
 <link rel="stylesheet" type="text/css" href="style.css">
 <a class="fruit" href="#">Home</a></span>
 <a class="fruit"  href="#">About</a></span>
 <a class="fruit"  href="#">Contact</a></span>
</html>

style.css:-

a:link{
 color:blue;
}

a:visited{
 color:purple;
}

a:hover{
 color:orange;
}
a:focus{
color:green;
}

a:active{
 color:red;
}

a:active{
 color:yellow;
}

0

根据@Sampson的答案,我是这样处理的 -

HTML:

  1. 每个页面都有一个带有content类的
    ,其中包含该页面的内容。页眉和页脚是分开的。
  2. 我为每个页面添加了一个唯一的content类。例如,如果我正在创建一个联系我们页面,我将把页面内容放在<section class="content contact-us"></section>中。
  3. 通过这种方式,我可以更轻松地在单个style.css中编写特定于页面的CSS。

<body>
    <header>
        <div class="nav-menu">
            <ul class="parent-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">Contact us</a></li>
                ...
            </ul>
        </div>
    </header>

    <section class="content contact-us">
        Content for contact us page goes here
    </section>

    <footer> ... </footer>

</body>

CSS:

  1. 我定义了一个单一的 active 类,它包含了活动菜单的样式。

.active {
    color: red;
    text-decoration: none;
}
<body>
    <header>
        <div class="nav-menu">
            <ul class="parent-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">Contact us</a></li>
                ...
            </ul>
        </div>
    </header>

    <section class="content contact-us">
        Content for contact us page goes here
    </section>

    <footer> ... </footer>

</body>

JavaScript:

  1. 现在在 JavaScript 中,我想要将菜单链接文本与 HTML 中定义的唯一类名进行比较。我正在使用 jQuery。
  2. 首先,我获取了所有菜单文本,并执行了一些字符串函数,使文本变为小写并用连字符替换空格,以便与类名匹配。
  3. 现在,如果 content 类具有与菜单文本相同的类(小写且没有空格),则将 active 类添加到菜单项中。

var $allMenu = $('.nav-menu > .parent-nav > li > a');
var $currentContent = $('.content');
$allMenu.each(function() {
  $singleMenuTitle = $(this).text().replace(/\s+/g, '-').toLowerCase();
  if ($currentContent.hasClass($singleMenuTitle)) {
    $(this).addClass('active');
  }
});
.active {
  color: red;
  text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <header>
    <div class="nav-menu">
      <ul class="parent-nav">
        <li><a href="#">Home</a></li>
        <li><a href="#">Contact us</a></li>
        ...
      </ul>
    </div>
  </header>

  <section class="content contact-us">
    Content for contact us page goes here
  </section>

  <footer> ... </footer>

</body>

我为什么要这样做?

  1. @Sampson的答案对我非常有效,但我注意到每次想添加新页面时都必须添加新代码。
  2. 此外,在我的项目中,body标签位于header.php文件中,这意味着我无法为每个页面编写唯一的类名。

0

你应该引用当前元素,而不是所有与你的选择器匹配的元素。

$("#mainMenu td").click(function() {
$(this).css('background-color', '#EDEDED');

});

我还建议您使用CSS类而不是以这种方式设置CSS属性。

就像这样:

$("#mainMenu td").click(function() {
$(this).addClass('selected');

});

连同;

#mainMenu td.selected {

背景颜色:#EDEDED;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接