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

Categories

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

javascript - Highlight the current menu item?

So basically I'm trying to give a class "current" to highlight the menu item for the current page. I've tried a couple of snippets I've seen on this website but most of them didn't work. This code is almost working for me, but the problem is although the current menu item is properly highlighted, Home button is also highlighted no matter which page I'm viewing. So like if I'm viewing "Archive" page, both Archive and Home are highlighted.

I'm using Wordpress to build the website by the way and I'm aware that Wordpress supports this effect but I'd like to achieve this without it.

HTML

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem">About</a></li>
</ul>

JS

jQuery(function($) {
        $('.navigation li a').each(function() {
            var target = $(this).attr('href');
            if(location.href.match(target)) {
            $(this).addClass('current');
            } else {
            $(this).removeClass('current');
            }
    });
});

I'm not really familiar with javascript so there might be some errors.

Thank you for reading this, and have a great new year.


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

1 Answer

0 votes
by (71.8m points)

The suggestion of wp_nav_menu is the correct way in WordPress, but if you're just looking for a quick solution and the menu won't change that often, you can get by with a check inside of each list item.

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem <?php if( is_front_page() ): echo 'current'; endif; ?>">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem <?php if( is_home() || is_archive() || is_single() ): echo 'current'; endif; ?>">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem <?php if( is_page('About') ): echo 'current'; endif; ?>">About</a></li>
</ul>

This makes use of WordPress' "Conditional Tags" which effectively come back as "true" or "false" for a given page. Note that the second link checks multiple blog/post conditions (assuming that that is for the blog).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...