简体   繁体   English

引导导航栏活动 State 不工作

[英]Bootstrap navbar Active State not working

I have bootstrap v3.我有引导程序 v3。

I use the class="active" on my navbar and it does not switch when I press menu items.我在navbar上使用class="active" ,当我按下菜单项时它不会切换。 I know how to do this with jQuery and build a click function but I'm thinking this functionality should be included in bootstrap?我知道如何使用jQuery执行此操作并构建单击 function 但我认为此功能应该包含在引导程序中? So maybe it is a JavaScript issue?那么也许是 JavaScript 问题?

Here is my header with my js/css/bootstrap files I have included:这是我的 header 和我包含的 js/css/bootstrap 文件:

<!-- Bootstrap CSS -->
<link rel="stylesheet" href= "/bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "/stylesheets/styles.css" />

<!--jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

<!-- Bootstrap JS -->
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/bootstrap/js/bootstrap-collapse.js"></script>
<script src="/bootstrap/js/bootstrap-transition.js"></script>

Here is my navbar code:这是我的navbar代码:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbarCollapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a class="navbar-brand" href="/index.php">MyBrand</a>
            </div>

            <div class="collapse navbar-collapse navbarCollapse">
                <ul class="nav navbar-nav navbar-right">
                    <li class="active">
                        <a href="/index.php">Home</a>
                    </li>

                    <li>
                        <a href="/index2.php"> Links</a>
                    </li>

                    <li>
                        <a href="/history.php">About</a>
                    </li>
                    <li>
                        <a href="/contact.php">Contact</a>
                    </li>

                    <li>
                        <a href="/login.php">Login</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

Am I setting this up right?我设置对了吗?

(On an unrelated note, but possible related? When the menu goes mobile, I click the menu button and it collapses. Pushing it again does not un-collapse it though. So this issue,. with the other, both signify wrong JavaScript setup perhaps?) (在不相关的注释上,但可能相关?当菜单移动时,我单击菜单按钮并折叠。再次按下它不会取消折叠它。所以这个问题,与另一个,都表示错误的 JavaScript 设置也许?)

You have included the minified Bootstrap js file and collapse/transition plugins while the docs state that:您已经包含了缩小的 Bootstrap js 文件和折叠/转换插件,而文档声明:

Both bootstrap.js and bootstrap.min.js contain all plugins in a single file. bootstrap.js 和 bootstrap.min.js 都在一个文件中包含所有插件。
Include only one.只包括一个。

and

For simple transition effects, include transition.js once alongside the other JS files.对于简单的过渡效果,将 transition.js 与其他 JS 文件一起包含一次。 If you're using the compiled (or minified) bootstrap.js, there is no need to include this—it's already there.如果您使用的是已编译(或缩小)的 bootstrap.js,则无需包含它——它已经存在。

So that could well be your problem for the minimize problem.因此,对于最小化问题,这很可能是您的问题。

For the active class, you have to manage it yourself, but it's just a line or two.对于活动类,你必须自己管理它,但它只是一两行。

Bootstrap 3:引导程序 3:

$(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});

Bootply: http://www.bootply.com/IsRfOyf0f9引导层:http: //www.bootply.com/IsRfOyf0f9

Bootstrap 4:引导程序 4:

$(".nav .nav-link").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).addClass("active");
});

Here was my solution for switching active pages这是我切换活动页面的解决方案

$(document).ready(function() {
  $('li.active').removeClass('active');
  $('a[href="' + location.pathname + '"]').closest('li').addClass('active'); 
});

This worked perfectly for me, because "window.location.pathname" also contains data before the real page name, eg directory/page.php.这对我来说非常有效,因为“window.location.pathname”还包含真实页面名称之前的数据,例如directory/page.php。 So the actual navbar link will only be set to active if the url contains this link.因此,只有当 url 包含此链接时,实际的导航栏链接才会被设置为活动。

$(document).ready(function() {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active', 
            window.location.pathname.indexOf($(this).find('a').attr('href')) > -1);
    }); 
});

With version 3.3.4 of bootstrap, on long html pages you can refer to sections of the pg.使用 bootstrap 的 3.3.4 版,在长 html 页面上,您可以参考 pg 的部分。 by class or id to manage the active navbar link with spy-scroll with the body element:通过类或 id 来管理带有 body 元素的 spy-scroll 的活动导航栏链接:

  <body data-spy="scroll" data-target="spy-scroll-id">

The data-target will be a div with the id="spy-scroll-id"数据目标将是一个 id="spy-scroll-id" 的 div

    <div id="spy-scroll-id" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#topContainer">Home</a></li>
        <li><a href="#details">About</a></li>
        <li><a href="#carousel-container">SlideShow</a></li>
      </ul>
    </div>

This should activate links by clicking without any javascript functions needed and will also automatically activate each link as you scroll through the corresponding linked sections of the page which a js onclick() will not.这应该通过单击来激活链接,而无需任何 javascript 函数,并且当您滚动浏览页面的相应链接部分时,它还会自动激活每个链接,而 js onclick() 不会。

All you need to do is simply add data-toggle="tab" to your link inside bootstrap navbar like this:您需要做的只是将data-toggle="tab"添加到引导导航栏中的链接中,如下所示:

<ul class="nav navbar-nav">
  <li class="active"><a data-toggle="tab" href="#">Home</a></li>
  <li><a data-toggle="tab" href="#">Test</a></li>
  <li><a data-toggle="tab" href="#">Test2</a></li>
</ul>

If you don't use anchor links, you can use something like this:如果你不使用锚链接,你可以使用这样的东西:

$(document).ready(function () {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active',
            '/' + $(this).find('a').attr('href') == window.location.pathname);
    });
});

With Bootstrap 4 you can use this:使用 Bootstrap 4,您可以使用它:

$(document).ready(function() {
    $(document).on('click', '.nav-item a', function (e) {
        $(this).parent().addClass('active').siblings().removeClass('active');
    });
});

This elegant solution did the trick for me.这个优雅的解决方案对我有用。 Any new ideas/suggestions are welcome.欢迎任何新的想法/建议。

$( document ).on( 'click', '.nav-list li', function ( e ) {
    $( this ).addClass( 'active' ).siblings().removeClass( 'active' );
} );

You can use jQuery's "siblings()" method to keep only the accessed item active and its siblings inactive.您可以使用 jQuery 的“siblings()”方法只保持访问的项目处于活动状态,而其兄弟项目处于非活动状态。

I use this.我用这个。 It's short, elegand and easy to understand.它简短、优雅且易于理解。

$(document).ready(function() {
    $('a[href$="' + location.pathname + '"]').addClass('active');
});

I've been struggling with this today, data-togle only worked if I'm on a single page application.我今天一直在为此苦苦挣扎,只有在我使用单页应用程序时数据切换才有效。

I'm not using ajax to load the content i'm actually making post request for other pages so the first js script was useless too.我没有使用 ajax 来加载我实际上是在为其他页面发出 post 请求的内容,所以第一个 js 脚本也没有用。 I solve it with this lines:我用这行来解决它:

var active = window.location.pathname;
$(".nav a[href|='" + active + "']").parent().addClass("active");

Bootstrap 4: navbar Active State working, just use .navbar-nav .nav-link classes Bootstrap 4:导航栏活动状态工作,只需使用 .navbar-nav .nav-link 类

 $(function () { // this will get the full URL at the address bar var url = window.location.href; // passes on every "a" tag $(".navbar-nav .nav-link").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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#">Other</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav>

I'm hope this will help to solve this problem.我希望这将有助于解决这个问题。

      var navlnks = document.querySelectorAll(".nav a");
        Array.prototype.map.call(navlnks, function(item) {

            item.addEventListener("click", function(e) {

                var navlnks = document.querySelectorAll(".nav a"); 

                Array.prototype.map.call(navlnks, function(item) {

                    if (item.parentNode.className == "active" || item.parentNode.className == "active open" ) {

                        item.parentNode.className = "";

                    } 

                }); 

                e.currentTarget.parentNode.className = "active";
            });
        });

I had some pain with this, using a dynamically generated list items - WordPress Stack.使用动态生成的列表项 - WordPress Stack,我对此感到有些痛苦。

Added this and it worked:添加了这个并且它起作用了:

$(document).ready(function () {
    $(".current-menu-item").addClass("active");
});

Will do it on the fly.将在飞行中进行。

I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.我一直在寻找可以在 bootstrap 4 导航栏和其他链接组上使用的解决方案。

For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed.出于某种原因,大多数解决方案都不起作用,尤其是那些尝试将“活动”添加到 onclick 链接的解决方案,因为当然,一旦单击链接,如果它会将您带到另一个页面,那么您添加的“活动”将不会是因为 DOM 已经改变了。 Many of the other solutions didn't work either because they often did not match the link or they matched more than one.许多其他解决方案也不起作用,因为它们通常与链接不匹配,或者匹配的链接不止一个。

This elegant solution is fine for links that are different ie: about.php, index.php, etc...这个优雅的解决方案适用于不同的链接,即:about.php、index.php 等......

$(function() {
   $('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});

However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.但是,当涉及到具有不同查询字符串(例如 index.php?tag=a、index.php?tag=b、index.php?tag=c)的相同链接时,它会将所有这些链接设置为活动状态,无论是点击了哪个匹配路径名而不是查询。

So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well.所以我尝试了这段匹配路径名和查询字符串的代码,它适用于所有带有查询字符串的链接,但是当点击 index.php 之类的链接时,它也会将类似的查询字符串链接设置为活动状态。 This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.这是因为如果链接中没有查询字符串,我的函数将返回一个空字符串,再次匹配路径名。

$(function() {
   $('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
   if (element === undefined)
      return "";
   else
      return '?' + element;
}

So in the end i abandoned this route and kept it simple and wrote this.所以最后我放弃了这条路线并保持简单并写了这个。

$('.navbar a').each(function(index, element) {
    //console.log(index+'-'+element.href);
    //console.log(location.href);
    /** look at each href in the navbar
      * if it matches the location.href then set active*/
    if (element.href === location.href){
        //console.log("---------MATCH ON "+index+" --------");
        $(element).addClass('active');
    }
});

It works on all links with or without query strings because element.href and location.href both return the full path.它适用于所有有或没有查询字符串的链接,因为 element.href 和 location.href 都返回完整路径。 For other menus etc you can simply change the parent class selector (navbar) for another ie:对于其他菜单等,您可以简单地将父类选择器(导航栏)更改为另一个,即:

$('.footer a').each(function(index, element)...

One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps.最后一件事似乎也很重要,那就是您正在使用的 js & css 库,但这可能是另一篇文章。 I hope this helps and contributes.我希望这会有所帮助和贡献。

Bootstrap 5.1引导程序 5.1

This is already implemented in bootstrap, and explained neatly in the documentation under the scrollspy section.这已经在 bootstrap 中实现,并在scrollspy部分下的文档中进行了简洁的解释。 Link to documentation 链接到文档

Steps to fix active state toggle:修复活动状态切换的步骤:

  1. set position:relative on your body element设置position:relative对于你的身体元素
  2. add id="navbar" to your navbar section.id="navbar"添加到您的导航栏部分。
  3. include this in your js file, or inside in the html:将此包含在您的 js 文件中,或包含在 html 中:
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar'
})

Class "active" is not managed out of the box with bootstrap. “活动”类不是通过引导程序开箱即用的。 In your case since you're using PHP you can see:在您的情况下,由于您使用的是 PHP,因此您可以看到:

How add class='active' to html menu with php 如何使用 php 将 class='active' 添加到 html 菜单

to assist you with a method of mostly automating it.以帮助您实现大部分自动化的方法。

For bootstrap mobile menu un-collapse after clicking a item you can use this对于单击项目后引导移动菜单取消折叠,您可以使用它

$("ul.nav.navbar-nav li a").click(function() {    

    $(".navbar-collapse").removeClass("in");
});

I m using bootstrap bare theme, here is the sample navbar code.我正在使用引导程序裸主题,这是示例导航栏代码。 Note the class name of the element -> .nav - as this is referred in java script.注意元素的类名 -> .nav - 因为这是在 java 脚本中引用的。

/ Collect the nav links, forms, and other content for toggling
    #bs-example-navbar-collapse-1.collapse.navbar-collapse
      %ul.nav.navbar-nav
        %li
          %a{:href => "/demo/one"} Page One
        %li
          %a{:href => "/demo/two"} Page Two
        %li
          %a{:href => "/demo/three"} Page Three

in the view page (or partial) add this :javascript, this needs to be executed every time page loads.在视图页面(或部分)中添加这个:javascript,这需要在每次页面加载时执行。

haml view snippet -> haml 视图片段 ->

- content_for :javascript do
  :javascript
      $(function () {
          $.each($('.nav').find('li'), function() {
              $(this).toggleClass('active',
                  $(this).find('a').attr('href') == window.location.pathname);
          });
      });

In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname.在 javascript 调试器中,确保“href”属性的值与 window.location.pathname 匹配。 This is slightly different than the solution by @Zitrax which helped me fixing my issue.这与帮助我解决问题的@Zitrax 的解决方案略有不同。

For AngularJS , you can use ng-class with a function like this:对于AngularJS ,您可以将ng-class与如下函数一起使用:

HTML -> HTML ->

<nav class="navbar navbar-default" ng-controller="NavCtrl as vm">
  <div class="container">
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav" >
        <li ng-class="vm.Helper.UpdateTabActive('Home')"><a href="#" ng-click>Home</a></li>
        <li ng-class="vm.Helper.UpdateTabActive('About')"><a href="#about">About</a></li>
        <li ng-class="vm.Helper.UpdateTabActive('Contact')"><a href="#contact">Contact</a></li>        
      </ul>
    </div>
</nav>

And controller和控制器

app.controller('NavCtrl', ['$scope', function($scope) {
    var vm = this;
    vm.Helper = {
        UpdateTabActive: function(sTab){
            return window.location.hash && window.location.hash.toLowerCase() == ("#/" + sTab).toLowerCase() ? 'active' : '';
        }
    }    
}]);

If you are using $location, then there won't be hash.如果您使用 $location,则不会有哈希。 So you can extract the required string from URL using $location因此,您可以使用$location从 URL 中提取所需的字符串

Following will not work in all cases -->以下不适用于所有情况-->

Using a scope variable like following will work only when clicked, but if the transition is done using $state.transitionTo or window.location or manually updating the URL, the Tab value will not be updated使用像下面这样的范围变量仅在单击时才有效,但如果使用$state.transitionTo或 window.location 或手动更新 URL 完成转换,则不会更新 Tab 值

<ul class="nav navbar-nav" ng-init="Tab='Home'">
   <li ng-class="Tab == 'Home' ? 'active' : ''"><a href="#" ng-click="Tab = 'Home'">Home</a></li>
   <li ng-class="Tab == 'About' ? 'active' : ''"><a href="#" ng-click="Tab = 'About'">About</a></li>
</ul>

Add this JavaScript on your main js file.将此 JavaScript 添加到您的主 js 文件中。

$(".navbar a").on("click", function(){
      $(".navbar").find(".active").removeClass("active");
      $(this).parent().addClass("active");
    });

I had to go a step forward because my file names were not the same as my nav bar titles.我必须向前迈出一步,因为我的文件名与导航栏标题不同。 ie my first nav bar link was HOME but the file name is index..即我的第一个导航栏链接是 HOME 但文件名是 index..

So just grab the pathname and match it.所以只需抓住路径名并匹配它。

Obviously this is a crude example and could be more efficient but it is highly custom need.显然,这是一个粗略的例子,可能更有效,但它是高度定制的需求。

var loc_path = location.pathname;
$('li.active').removeClass('active');



if(loc_path.includes('index')){
    $('li :eq(0)').addClass('active');
}else if(loc_path.includes('blog')){
    $('li :eq(2)').addClass('active');
}else if(loc_path.includes('news')){
    $('li :eq(3)').addClass('active');
}else if(loc_path.includes('house')){
    $('li :eq(4)').addClass('active');
}

Bootstrap 4 solution that worked for me:对我有用的 Bootstrap 4 解决方案:

$(document).ready(function() {
//You can name this function anything you like
function activePage(){
//When user lands on your website location.pathname is equal to "/" and in 
//that case it will add "active" class to all links
//Therefore we are going to remove first character "/" from the pathname
  var currentPage = location.pathname;
  var slicedCurrentPage = currentPage.slice(1);
//This will add active class to link for current page
  $('.nav-link').removeClass('active');
  $('a[href*="' + location.pathname + '"]').closest('li').addClass('active');
//This will add active class to link for index page when user lands on your website
     if (location.pathname == "/") {
         $('a[href*="index"]').closest('li').addClass('active');
    }
}
//Invoke function
activePage();
});

This will only work if href contains location.pathname !这仅在href包含location.pathname时才有效!

If you are testing your site on your own pc (using wamp, xampp, lamp, etc...) and your site is located in some subfolder then your path is actually "/somefolder/something.php", so don't get confused.如果您在自己的电脑上测试您的网站(使用 wamp、xampp、lamp 等)并且您的网站位于某个子文件夹中,那么您的路径实际上是“/somefolder/something.php”,所以不要得到使困惑。

I would suggest if you are unsure to use following code so you can make sure what is the correct location.pathname :如果您不确定是否使用以下代码,我建议您确保正确的location.pathname是什么:

$(document).ready(function() {
  alert(location.pathname);
});

the next answer is for those who have a multi-level menu:下一个答案适用于拥有多级菜单的人:

var url = window.location.href;

var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
    var el = els[i];
    if (el.href === url) {
       el.classList.add("active");
       var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent
       parent.classList.add("active");
    }
}

示例它是如何工作的

As someone who doesn't know javascript, here's a PHP method that works for me and is easy to understand.作为不懂javascript的人,这里有一个对我有用且易于理解的PHP方法。 My whole navbar is in a PHP function that is in a file of common components I include from my pages.我的整个导航栏位于一个 PHP 函数中,该函数位于我的页面中包含的常见组件文件中。 So for example in my 'index.php' page I have... `因此,例如在我的“index.php”页面中,我有...`

<?php
   $calling_file = basename(__FILE__);
   include 'my_common_includes.php';    // Going to use my navbar function "my_navbar"
   my_navbar($calling_file);    // Call the navbar function
 ?>

Then in the 'my_common_includes.php' I have...然后在'my_common_includes.php'中我有......

<?php
   function my_navbar($calling_file)
   {
      // All your usual nabvbar code here up to the menu items
      if ($calling_file=="index.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="index.php">Home</a>
</li>';
      if ($calling_file=="about.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="about.php">About</a>
</li>';
      if ($calling_file=="galleries.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="galleries.php">Galleries</a>
</li>';
       // etc for the rest of the menu items and closing out the navbar
     }
  ?>

Bootstrap 4 requires you to target the li item for active classes. Bootstrap 4 要求您将li项目定位为活动类。 In order to do that you have to find the parent of the a .为此,您必须找到a的父级。 The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. a的“hitbox”与li一样大,但由于 JS 中的事件冒泡,它会返回a事件。 So you have to manually add it to its parent.因此,您必须手动将其添加到其父级。

  //set active navigation after click
  $(".nav-link").on("click", (event) => {
    $(".navbar-nav").find(".active").removeClass('active');
    $(event.target).parent().addClass('active');
  });

I tried about first 5 solutions and different variations of them, but they didn't work for me.我尝试了前 5 个解决方案和它们的不同变体,但它们对我不起作用。

Finally I got it working with these two functions.最后我让它与这两个功能一起工作。

$(document).on('click', '.nav-link', function () {
    $(".nav-item").find(".active").removeClass("active");
})

$(document).ready(function() {
    $('a[href="' + location.pathname + '"]').closest('.nav-item').addClass('active'); 
});

when use header.php for every page for the navbar code, the jquery does not work, the active is applied and then removed, a simple solution, is as follows navbar代码每页使用header.php时,jquery不起作用,先应用active再移除,简单的解决方法,如下

on every page set variable <?php $pageName = "index"; ?>在每个页面上设置变量<?php $pageName = "index"; ?> <?php $pageName = "index"; ?> on Index page and similarly <?php $pageName = "contact"; ?> <?php $pageName = "index"; ?>在索引页面上,类似地<?php $pageName = "contact"; ?> <?php $pageName = "contact"; ?> on Contact us page <?php $pageName = "contact"; ?>在联系我们页面

then call the header.php (ie the nav code is in header.php) <?php include('header.php'); >然后调用 header.php (即导航代码在 header.php) <?php include('header.php'); > <?php include('header.php'); >

in the header.php ensure that each nav-link is as follows在 header.php 中确保每个导航链接如下

<a class="nav-link <?php if ($page_name == 'index') {echo "active";} ?> href="index.php">Home</a>

<a class="nav-link <?php if ($page_name == 'contact') {echo "active";} ?> href="contact.php">Contact Us</a>

hope this helps cause i have spent days to get the jquery to work but failed,希望这会有所帮助,因为我花了几天时间让 jquery 工作但失败了,

if someone would kindly explain what exactly is the issue when the header.php is included and then page loads... why the jquery fails to add the active class to the nav-link..??如果有人愿意解释包含 header.php 然后页面加载时究竟是什么问题......为什么 jquery 无法将活动类添加到导航链接......?

For Bootstrap 5 I use the folowing to keep the dropdown items active after navigating to a url.对于 Bootstrap 5,我使用以下方法在导航到 url 后保持下拉项处于活动状态。

 <li class="nav-item dropdown text-center ">
          <a class="nav-link dropdown-toggle dropdown-toggle-split" href="#" id="navbarDropdown1" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Clienten
          </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdown1">
          <li><h6 class="dropdown-header">Iedereen</h6></li>
            <li><a class="dropdown-item " aria-current="page" href="/submap/IndexClients.php">Overzicht</a></li>
            
            <li><hr class="dropdown-divider"></li>
            <li><h6 class="dropdown-header">Persoonlijk</h6></li>
            <li><a class="dropdown-item" aria-current="page" href="/submap/IndexClientsP.php">Overzicht (<?= $usernamesession ?>)</a></li>
            
          </ul>
        </li>

<script>
$(document).ready(function() {

  $('a.active').removeClass('active');
var active = window.location.pathname;
    $('a[href="' + active + '"]').closest('.dropdown-item').addClass('active'); 
});

</script>

With bootstrap 4 I missed from the documentation that I needed to also add使用 bootstrap 4,我错过了我还需要添加的文档

$('#myList a').on('click', function (e) {
    e.preventDefault()
    $(this).tab('show')
})

https://getbootstrap.com/docs/4.0/components/list-group/ https://getbootstrap.com/docs/4.0/components/list-group/

alot of people need a jq/js solution for non ajax-request for bs4 so i ve worked my way to this solution that works just fine first we get the currant path stripped from all queries and have it stored second we loop through nav-links attribute values after we check that they aren't empty finally we do a match between the values and the path) PS: we don't need to check for an existing active class since this is non ajax-request so make sure u don't hard code an active class in ur html很多人需要一个 jq/js 解决方案来解决 bs4 的非 ajax 请求,所以我已经按照我的方法找到了这个解决方案,它工作得很好,首先我们从所有查询中删除醋栗路径并存储它,然后我们循环遍历导航链接属性值在我们检查它们不为空之后最后我们在值和路径之间进行匹配) PS:我们不需要检查现有的活动 class 因为这是非 ajax 请求所以确保你不要'在您的 html 中硬编码一个活动的 class

    $(function(){
    let path = location.pathname.split('/').pop();
    $('#mainNav li a').each(function(){
        var $this = $(this);
        if ($this.length > 0) {
            var hrefValue = $this.attr("href").split('?')[0];
            if(hrefValue == path)
            {
                $this.addClass('active');
            }
        }
    })
})

Change your class更改您的 class

<li class="nav-item active">
   <a href="contact.php" class="nav-link">Contact</a>
</li>

and add in your.css, with properties equals of your:hover:并添加您的.css,其属性等于您的:hover:

  #navbar .active a{
    color:rgb(150, 0, 0);
    text-decoration: none;
    font-weight: bold;   
  }
$(document).ready(function() {
            
   var url = window.location.href;
            
   $('a[href*="'+url+'"]').addClass("active");
            
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM