突出显示当前页面的导航菜单

发布于 2024-10-11 04:55:13 字数 172 浏览 6 评论 0原文

在带有一些导航链接的页面中,我希望当前页面的链接突出显示,就像这样:

>链接“HTML 属性”突出显示(粗体),因为此链接将跳转到当前页面。

我知道这可以手动实现(只是突出显示相应的链接,但是有一些聪明的方法吗?动态和自动突出显示正确的链接?

In a page with some navigation links,I want the link of the current page are hightlighted,just like this:

alt text

The link "HTML Attributes" is highlighted(bolded) since this link will take one to the current page.

I know this can be implemented manually(just hightlighted the according link,but is there some smart way? highlight the right link dynamically and automatically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

奈何桥上唱咆哮 2024-10-18 04:55:13

CSS:

.topmenu ul li.active a, .topmenu ul li a:hover {
    text-decoration:none;
    color:#fff;
    background:url(../images/menu_a.jpg) no-repeat center top;
}

JavaScript:

<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script> 

<script type="text/javascript">
    $(function() {
        // this will get the full URL at the address bar
        var url = window.location.href;

        // passes on every "a" tag
        $(".topmenu a").each(function() {
            // checks if its the same on the address bar
            if (url == (this.href)) {
                $(this).closest("li").addClass("active");
                //for making parent of submenu active
               $(this).closest("li").parent().parent().addClass("active");
            }
        });
    });        
</script>

Html 代码:

<div class="topmenu">
    <ul>
        <li><a href="Default.aspx">Home</a></li>
        <li><a href="NewsLetter.aspx">Newsletter</a></li>
        <li><a href="#">Forms</a></li>
        <li><a href="#">Mail</a></li>
        <li><a href="#">Service</a></li>
        <li style="border:none;"><a href="#">HSE</a></li>
        <li><a href="#">MainMenu2</a>
           <ul>
              <li>submenu1</li>
              <li>submenu2</li>
              <li>submenu3</li>
          </ul>
       </li>
    </ul>
</div>

CSS:

.topmenu ul li.active a, .topmenu ul li a:hover {
    text-decoration:none;
    color:#fff;
    background:url(../images/menu_a.jpg) no-repeat center top;
}

JavaScript:

<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script> 

<script type="text/javascript">
    $(function() {
        // this will get the full URL at the address bar
        var url = window.location.href;

        // passes on every "a" tag
        $(".topmenu a").each(function() {
            // checks if its the same on the address bar
            if (url == (this.href)) {
                $(this).closest("li").addClass("active");
                //for making parent of submenu active
               $(this).closest("li").parent().parent().addClass("active");
            }
        });
    });        
</script>

Html Code:

<div class="topmenu">
    <ul>
        <li><a href="Default.aspx">Home</a></li>
        <li><a href="NewsLetter.aspx">Newsletter</a></li>
        <li><a href="#">Forms</a></li>
        <li><a href="#">Mail</a></li>
        <li><a href="#">Service</a></li>
        <li style="border:none;"><a href="#">HSE</a></li>
        <li><a href="#">MainMenu2</a>
           <ul>
              <li>submenu1</li>
              <li>submenu2</li>
              <li>submenu3</li>
          </ul>
       </li>
    </ul>
</div>
固执像三岁 2024-10-18 04:55:13

您可以将页面主体的 id 设置为代表当前页面的某个值。然后,为菜单中的每个元素设置一个特定于该菜单项的类。在 CSS 中,您可以设置一条规则来专门突出显示菜单项...

这可能没有多大意义,所以这里有一个示例:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

在 page1.html 中,您可以将正文的 id 设置为: id="page1"

最后,在 CSS 中,您将看到如下内容:

#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

您需要更改每个页面的 ID,但 CSS 保持不变,这一点很重要,因为 CSS 通常会被缓存,并且可能需要强制刷新才能更新。

它不是动态的,但它是一种简单的方法,您只需使用 PHP 或类似工具包含模板文件中的菜单 html 即可。

You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...

That probably didn't make much sense, so here's an example:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

In the page1.html, you would set the id of the body to: id="page1".

Finally in your CSS you have something like the following:

#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.

It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.

想你只要分分秒秒 2024-10-18 04:55:13

在我看来,你需要当前的代码,如“.menu-current css”,我问的是同样的代码,它的工作原理就像一个魅力,你可以尝试这样的东西,可能仍然是一些配置

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}

It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm, You could try something like this might still be some configuration

a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}


div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}
寄意 2024-10-18 04:55:13
<script id="add-active-to-current-page-nav-link" type="text/javascript">
    function setSelectedPageNav() {
        var pathName = document.location.pathname;
        if ($("nav ul li a") != null) {
            var currentLink = $("nav ul li a[href='" + pathName + "']");
            currentLink.addClass("active");
        }
    }
    setSelectedPageNav();
</script>
<script id="add-active-to-current-page-nav-link" type="text/javascript">
    function setSelectedPageNav() {
        var pathName = document.location.pathname;
        if ($("nav ul li a") != null) {
            var currentLink = $("nav ul li a[href='" + pathName + "']");
            currentLink.addClass("active");
        }
    }
    setSelectedPageNav();
</script>
帅的被狗咬 2024-10-18 04:55:13

Css类在这里

<style type="text/css">
.mymenu
{
    background-color: blue;
    color: white;
}
.newmenu
{
    background-color: red;
    color: white;
}
</style>

让你的HTML像这样,将url设置为id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

在这里编写javascript,将此javascript放在HTML代码之后。

    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();

Css classes are here

<style type="text/css">
.mymenu
{
    background-color: blue;
    color: white;
}
.newmenu
{
    background-color: red;
    color: white;
}
</style>

Make your HTML like this, Set url as id

  <div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
  <div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>

Here write javascript, put this javascript after the HTML code.

    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();
悲歌长辞 2024-10-18 04:55:13

我通常会在服务器端处理这个问题(指 PHP、ASP.NET 等)。这个想法是,当页面加载时,服务器端控制机制(可能通过设置 CSS 值),该机制反映在客户端看到的结果 HTML 中。

I would normally handle this on the server-side of things (meaning PHP, ASP.NET, etc). The idea is that when the page is loaded, the server-side controls the mechanism (perhaps by setting a CSS value) that is reflected in the resulting HTML the client sees.

空城之時有危險 2024-10-18 04:55:13

您可以使用 Javascript 解析 DOM,并突出显示与第一个 h1 标签具有相同标签的链接。但我认为这是矫枉过正=)

最好设置一个包含页面标题的var,并使用它在相应的链接处添加一个类。

You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)

It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.

北凤男飞 2024-10-18 04:55:13

我通常使用一个类来实现这一点。实现任何内容都非常简单,导航链接、超链接等。

在 CSS 文档中插入:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

这​​将使列表项的悬停状态具有红色文本和白色背景。将当前类附加到“当前”页面上的任何链接,它将显示相同的样式。

我是您的 HTML 插入内容:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>

I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.

In your CSS document insert:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.

Im your HTML insert:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>
究竟谁懂我的在乎 2024-10-18 04:55:13

请查看以下内容:

这是有效的:

1.) 顶部菜单按钮可见并正确突出显示

2.) 菜单按钮直到顶部才可见菜单被点击

这里需要做的工作:

1.)当点击子菜单时,寻找新页面以保持所选子菜单打开(我将突出显示所选子菜单按钮关于导航的进一步说明)

请参阅此处的代码:
http://jsbin.com/ePawaju/1/edit

或此处:
http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

我需要把这个头部的脚本?最好的地方在哪里?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery 对我来说是新的,任何帮助将不胜感激:)
var 子菜单;

$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});

Please Look at the following:

Here is what's working:

1.) top menu buttons are visible and highlight correctly

2.) sub menu buttons are not visible until top menu is clicked

Here is what needs work:

1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)

Please see code here:
http://jsbin.com/ePawaju/1/edit

or here:
http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

Do I need to put this script in the head section? Where is the best place?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery is new to me, any help would greatly be appreciated :)
var submenu;

$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});
审判长 2024-10-18 04:55:13

JavaScript:

<script type="text/javascript">
    $(function() { 
        var url = window.location;
        $('ul.nav a').filter(function() {
            return this.href == url;
        }).parent().parent().parent().addClass('active');
    });   
</script>

CSS:

.active{
    color: #fff;
    background-color: #080808;
}

HTML:

<ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>
                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
                                </li>
                                <li>
                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
                                </li>
                          </ul>
                     </li>
</ul>

JavaScript:

<script type="text/javascript">
    $(function() { 
        var url = window.location;
        $('ul.nav a').filter(function() {
            return this.href == url;
        }).parent().parent().parent().addClass('active');
    });   
</script>

CSS:

.active{
    color: #fff;
    background-color: #080808;
}

HTML:

<ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>
                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
                                </li>
                                <li>
                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
                                </li>
                          </ul>
                     </li>
</ul>
寻找我们的幸福 2024-10-18 04:55:13

我更喜欢使代码尽可能简短明了,并避免使用任何外部文件(包括 jquery)。
所以这就是我在研究了几个主题后得到的结果——使用简单的 Javascript 和 CSS,不需要 jquery。

在菜单完成后立即放置 javascript 代码(在关闭 ul、div 等之后) - 代码片段中的代码应位于

<script>
    function highlightCurrentURL() {
      var a = document.getElementById("navig").getElementsByTagName("a");
      for (var i = 0; i < a.length; i++) {
        if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
          a[i].className = "current";
        }
      }
    }
    // 
    window.onload = function() {
      highlightCurrentURL();
    }
</script>

// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) {
  // for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
  console.log(a[i].href);
  // strip off any local (withing page) anchors (symbol "#" and what follows after)
  if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
    // add a class to the matched link (<a>), define it in CSS
    a[i].className = "current";
  }
}
nav#navig a.current {
  color: red;
}
<nav id="navig">
  <ul>
    <li><a href="/url1">url1 name</a></li>
    <li><a href="/url2">url2 name</a></li>
    <li><a href="/url3">url3 name</a></li>
    <li><a href="https://stacksnippets.net/js#test_page_anchor">Test link matching current URL</a></li>
  </ul>
</nav>

I prefer to keep code as short and plain as possible, and avoid using any external files (jquery included).
So here is what I've ended up with for myself after researching several topics - using plain Javascript and CSS, no need for jquery.

Put javascript code right after the menu finishes (after closing ul, div, whatever) - code from a snippet should be between <script>Copy code here</script>
That would allow for a script to execute right after menu will be loaded.
If you want to call it as a function on page load, then link will change only after all elements (including images) are loaded – place this code in a function, call it on page load, the code itself put before the closing tag like so:

<script>
    function highlightCurrentURL() {
      var a = document.getElementById("navig").getElementsByTagName("a");
      for (var i = 0; i < a.length; i++) {
        if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
          a[i].className = "current";
        }
      }
    }
    // 
    window.onload = function() {
      highlightCurrentURL();
    }
</script>

// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) {
  // for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
  console.log(a[i].href);
  // strip off any local (withing page) anchors (symbol "#" and what follows after)
  if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
    // add a class to the matched link (<a>), define it in CSS
    a[i].className = "current";
  }
}
nav#navig a.current {
  color: red;
}
<nav id="navig">
  <ul>
    <li><a href="/url1">url1 name</a></li>
    <li><a href="/url2">url2 name</a></li>
    <li><a href="/url3">url3 name</a></li>
    <li><a href="https://stacksnippets.net/js#test_page_anchor">Test link matching current URL</a></li>
  </ul>
</nav>

扶醉桌前 2024-10-18 04:55:13

您可以使用 PHP 或 Jquery 以多种方式实现此目的。这是我在我的项目中实现它的方法。

<?php 
    //set a default value when the page is not an active page  

    $dashboard_active=$profile_active=$home_active='inactive_page';
    
    //get the Name of the current page;
    //in simple php set the NAME of the php file similar to the link variable
    //example set page name as home if you are going to print the variable $home/$home_active

    $page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

    //OR
    //in Laravel

    $page=Route::currentRouteName();
    
    //OR
    //send page value from the controller
    

    ${$page."_active"} = 'active_page';

//the above method will change the value of the current active page variable

        ?>

在 html 中打印 php 数据

<ul class="nav navbar-nav ">
<li ><a href="www.p.com/dashboard"><span class=" <?php echo $dashboard_active ?> ">  Dashboard</span></a></li>
<li ><a href="www.p.com/profile"><span class=" <?php echo $profile_active ?>"> Profile</span></a></li>
<li ><a href="www.p.com/home"><span class=" <?php echo $home_active ?>">Home</span></a></li>
</ul>

执行此操作,您需要添加此内容

<script>
    //with jquery
$(function(){
    //works when your href is an absolute href instead of relative href
        $('a').each(function(){
            if ($(this).prop('href') == window.location.href) {                
                $(this).children('span').addClass('active_page');  
                //to make the link only active
                $(this).addClass('active_page');   
                //to make the list active 
                $(this).panrent('li').addClass('active_page');   
            }
        });
    });
</script>

您也可以使用 Jquery在 CSS 中

<style>    
.active_page:hover,.inactive_page:hover
{
  background-color: rgb(218, 119, 5)!important;
    color: white;
}
.active_page
{
  background-color: green!important;
    color: white!important;      
}

.inactive_page
{
    color:#fff;    
}
</style>

You can Implement this in various ways usinh PHP or Jquery. Here is how I have implemented it in my Projects.

<?php 
    //set a default value when the page is not an active page  

    $dashboard_active=$profile_active=$home_active='inactive_page';
    
    //get the Name of the current page;
    //in simple php set the NAME of the php file similar to the link variable
    //example set page name as home if you are going to print the variable $home/$home_active

    $page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

    //OR
    //in Laravel

    $page=Route::currentRouteName();
    
    //OR
    //send page value from the controller
    

    ${$page."_active"} = 'active_page';

//the above method will change the value of the current active page variable

        ?>

In html print the php data

<ul class="nav navbar-nav ">
<li ><a href="www.p.com/dashboard"><span class=" <?php echo $dashboard_active ?> ">  Dashboard</span></a></li>
<li ><a href="www.p.com/profile"><span class=" <?php echo $profile_active ?>"> Profile</span></a></li>
<li ><a href="www.p.com/home"><span class=" <?php echo $home_active ?>">Home</span></a></li>
</ul>

YOu can also do this with Jquery

<script>
    //with jquery
$(function(){
    //works when your href is an absolute href instead of relative href
        $('a').each(function(){
            if ($(this).prop('href') == window.location.href) {                
                $(this).children('span').addClass('active_page');  
                //to make the link only active
                $(this).addClass('active_page');   
                //to make the list active 
                $(this).panrent('li').addClass('active_page');   
            }
        });
    });
</script>

IN the CSS you need to add this

<style>    
.active_page:hover,.inactive_page:hover
{
  background-color: rgb(218, 119, 5)!important;
    color: white;
}
.active_page
{
  background-color: green!important;
    color: white!important;      
}

.inactive_page
{
    color:#fff;    
}
</style>
夜唯美灬不弃 2024-10-18 04:55:13

仅使用 CSS。您可以使用 CSS 属性选择器为每个页面选择适当的链接。

例如 about.html 看起来像这样。

CSS

a[href="/about"] {
    font-weight: bold;
}

HTML

<nav>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
</nav>

Using CSS only. You can use CSS Attribute selector to select an appropriate link for every page.

For example about.html will look like this.

CSS

a[href="/about"] {
    font-weight: bold;
}

HTML

<nav>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
</nav>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文