Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - Active Menu Highlight CSS

I want to highlight the current menu you have click. I'm using CSS, but it is now working.

here is my css code:

#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; }

here is my 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>

This is what I like when I hover and if the menu is active

This is what I like when I hover and if the menu is active

Hover is okay, The problem is when I after click the menu the black ground is not display


@Jonathan, I have already solve it and it is more simply than what you have gave.

this is my answer:

$(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");
        }
    });
});

then on my css file:

.active { background-color: #000; }
/* to override the existing css for "a" tag */
#sub-header .active a{ color: #fff; }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a class to the body of each page:

<body class="home">

Or if you're on the contact page:

<body class="contact">

Then take this into consideration when you're creating your styles:

#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; }

Lastly, apply class names to your list items:

<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>

This point, whenever you're on the body.home page, your li.home a link will have default styling indicating it is the current page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...