jQuery current page highlight

旧街凉风 提交于 2021-02-10 14:21:12

问题


How can I use jQuery to highlight the current page? In other words, add a "current" class to the a element of the current page.

Here's my code:

    <div id="nav">
        <ul>
            <li><a href="../articles/">Articles</a></li>
            <li><a href="../photos/">Photos</a></li>
            <li><a href="../info/">Earthquake Info</a></li>
        </ul>
    </div>

I've researched several different approaches, but most of them rely on linking to pages (i.e. articles.html) instead of directories (i.e. ../articles/).

I've seen the body/ID class method and would prefer an automatic jQuery solution.

Here's my site.


回答1:


This is how I do it on my personal site. (Link Here)

<ul id="navLinks">
    <li><a id="homeLink" href="/">Home</a></li>
    <li><a id="blogLink" href="/blog/">Blog</a></li>
    <li><a id="photosLink" href="/photo-gallery/">Photos</a></li>
    <li><a id="portfolioLink" href="/portfolio/">About Me</a></li>
    <li><a id="contactLink" href="/contact/">Contact</a></li>
</ul>



var section = window.location.pathname;

if (section == '/') { $('#homeLink').attr('class', 'selected'); }
if (section.substring(0, 5) == "/blog") { $('#blogLink').attr('class', 'selected'); }
if (section.substring(0, 9) == "/articles") { $('#blogLink').attr('class', 'selected'); }
if (section.substring(0, 8) == "/contact") { $('#contactLink').attr('class', 'selected'); }
if (section.substring(0, 14) == "/photo-gallery") { $('#photosLink').attr('class', 'selected'); }
if (section.substring(0, 10) == "/portfolio") { $('#portfolioLink').attr('class', 'selected'); }



回答2:


You could do this with document.location.href and spliting the string.

Run a loop through your elements compare them to splited string and add class to right one.




回答3:


this should sort you out.
you might need to tweak it slightly to work with folders..




回答4:


While I couldn't find a jQuery solution, I did find a nice Javascript alternative.



来源:https://stackoverflow.com/questions/7761328/jquery-current-page-highlight

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