jQuery Menu - Active State Based on URL

前端 未结 4 1001
说谎
说谎 2021-01-03 11:38

I am just trying to retrofit an active state into a static html menu. The menu has the following structure: -

ul id=\"MenuBar1\" cl
4条回答
  •  臣服心动
    2021-01-03 12:27

    You can get the current path with JavaScript using window.location.pathname. You can check with jQuery using something like:

    $("#navbar a[href=" + window.location.pathname + "]").addClass('active');
    

    This will add the active class to all anchors in #navbar that have the same href attribute as the current path. You may need to trim the leading slash.

提交回复
热议问题