簡體   English   中英

引導導航欄活動 State 不工作

[英]Bootstrap navbar Active State not working

我有引導程序 v3。

我在navbar上使用class="active" ,當我按下菜單項時它不會切換。 我知道如何使用jQuery執行此操作並構建單擊 function 但我認為此功能應該包含在引導程序中? 那么也許是 JavaScript 問題?

這是我的 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>

這是我的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>

我設置對了嗎?

(在不相關的注釋上,但可能相關?當菜單移動時,我單擊菜單按鈕並折疊。再次按下它不會取消折疊它。所以這個問題,與另一個,都表示錯誤的 JavaScript 設置也許?)

您已經包含了縮小的 Bootstrap js 文件和折疊/轉換插件,而文檔聲明:

bootstrap.js 和 bootstrap.min.js 都在一個文件中包含所有插件。
只包括一個。

對於簡單的過渡效果,將 transition.js 與其他 JS 文件一起包含一次。 如果您使用的是已編譯(或縮小)的 bootstrap.js,則無需包含它——它已經存在。

因此,對於最小化問題,這很可能是您的問題。

對於活動類,你必須自己管理它,但它只是一兩行。

引導程序 3:

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

引導層:http: //www.bootply.com/IsRfOyf0f9

引導程序 4:

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

這是我切換活動頁面的解決方案

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

這對我來說非常有效,因為“window.location.pathname”還包含真實頁面名稱之前的數據,例如directory/page.php。 因此,只有當 url 包含此鏈接時,實際的導航欄鏈接才會被設置為活動。

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

使用 bootstrap 的 3.3.4 版,在長 html 頁面上,您可以參考 pg 的部分。 通過類或 id 來管理帶有 body 元素的 spy-scroll 的活動導航欄鏈接:

  <body data-spy="scroll" data-target="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>

這應該通過單擊來激活鏈接,而無需任何 javascript 函數,並且當您滾動瀏覽頁面的相應鏈接部分時,它還會自動激活每個鏈接,而 js onclick() 不會。

您需要做的只是將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>

如果你不使用錨鏈接,你可以使用這樣的東西:

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

使用 Bootstrap 4,您可以使用它:

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

這個優雅的解決方案對我有用。 歡迎任何新的想法/建議。

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

您可以使用 jQuery 的“siblings()”方法只保持訪問的項目處於活動狀態,而其兄弟項目處於非活動狀態。

我用這個。 它簡短、優雅且易於理解。

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

我今天一直在為此苦苦掙扎,只有在我使用單頁應用程序時數據切換才有效。

我沒有使用 ajax 來加載我實際上是在為其他頁面發出 post 請求的內容,所以第一個 js 腳本也沒有用。 我用這行來解決它:

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

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>

我希望這將有助於解決這個問題。

      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";
            });
        });

使用動態生成的列表項 - WordPress Stack,我對此感到有些痛苦。

添加了這個並且它起作用了:

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

將在飛行中進行。

我一直在尋找可以在 bootstrap 4 導航欄和其他鏈接組上使用的解決方案。

出於某種原因,大多數解決方案都不起作用,尤其是那些嘗試將“活動”添加到 onclick 鏈接的解決方案,因為當然,一旦單擊鏈接,如果它會將您帶到另一個頁面,那么您添加的“活動”將不會是因為 DOM 已經改變了。 許多其他解決方案也不起作用,因為它們通常與鏈接不匹配,或者匹配的鏈接不止一個。

這個優雅的解決方案適用於不同的鏈接,即:about.php、index.php 等......

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

但是,當涉及到具有不同查詢字符串(例如 index.php?tag=a、index.php?tag=b、index.php?tag=c)的相同鏈接時,它會將所有這些鏈接設置為活動狀態,無論是點擊了哪個匹配路徑名而不是查詢。

所以我嘗試了這段匹配路徑名和查詢字符串的代碼,它適用於所有帶有查詢字符串的鏈接,但是當點擊 index.php 之類的鏈接時,它也會將類似的查詢字符串鏈接設置為活動狀態。 這是因為如果鏈接中沒有查詢字符串,我的函數將返回一個空字符串,再次匹配路徑名。

$(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;
}

所以最后我放棄了這條路線並保持簡單並寫了這個。

$('.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');
    }
});

它適用於所有有或沒有查詢字符串的鏈接,因為 element.href 和 location.href 都返回完整路徑。 對於其他菜單等,您可以簡單地將父類選擇器(導航欄)更改為另一個,即:

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

最后一件事似乎也很重要,那就是您正在使用的 js & css 庫,但這可能是另一篇文章。 我希望這會有所幫助和貢獻。

引導程序 5.1

這已經在 bootstrap 中實現,並在scrollspy部分下的文檔中進行了簡潔的解釋。 鏈接到文檔

修復活動狀態切換的步驟:

  1. 設置position:relative對於你的身體元素
  2. id="navbar"添加到您的導航欄部分。
  3. 將此包含在您的 js 文件中,或包含在 html 中:
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar'
})

“活動”類不是通過引導程序開箱即用的。 在您的情況下,由於您使用的是 PHP,因此您可以看到:

如何使用 php 將 class='active' 添加到 html 菜單

以幫助您實現大部分自動化的方法。

對於單擊項目后引導移動菜單取消折疊,您可以使用它

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

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

我正在使用引導程序裸主題,這是示例導航欄代碼。 注意元素的類名 -> .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

在視圖頁面(或部分)中添加這個:javascript,這需要在每次頁面加載時執行。

haml 視圖片段 ->

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

在 javascript 調試器中,確保“href”屬性的值與 window.location.pathname 匹配。 這與幫助我解決問題的@Zitrax 的解決方案略有不同。

對於AngularJS ,您可以將ng-class與如下函數一起使用:

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>

和控制器

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' : '';
        }
    }    
}]);

如果您使用 $location,則不會有哈希。 因此,您可以使用$location從 URL 中提取所需的字符串

以下不適用於所有情況-->

使用像下面這樣的范圍變量僅在單擊時才有效,但如果使用$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>

將此 JavaScript 添加到您的主 js 文件中。

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

我必須向前邁出一步,因為我的文件名與導航欄標題不同。 即我的第一個導航欄鏈接是 HOME 但文件名是 index..

所以只需抓住路徑名並匹配它。

顯然,這是一個粗略的例子,可能更有效,但它是高度定制的需求。

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 解決方案:

$(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();
});

這僅在href包含location.pathname時才有效!

如果您在自己的電腦上測試您的網站(使用 wamp、xampp、lamp 等)並且您的網站位於某個子文件夾中,那么您的路徑實際上是“/somefolder/something.php”,所以不要得到使困惑。

如果您不確定是否使用以下代碼,我建議您確保正確的location.pathname是什么:

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

下一個答案適用於擁有多級菜單的人:

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");
    }
}

示例它是如何工作的

作為不懂javascript的人,這里有一個對我有用且易於理解的PHP方法。 我的整個導航欄位於一個 PHP 函數中,該函數位於我的頁面中包含的常見組件文件中。 因此,例如在我的“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
 ?>

然后在'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 要求您將li項目定位為活動類。 為此,您必須找到a的父級。 a的“hitbox”與li一樣大,但由於 JS 中的事件冒泡,它會返回a事件。 因此,您必須手動將其添加到其父級。

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

我嘗試了前 5 個解決方案和它們的不同變體,但它們對我不起作用。

最后我讓它與這兩個功能一起工作。

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

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

navbar代碼每頁使用header.php時,jquery不起作用,先應用active再移除,簡單的解決方法,如下

在每個頁面上設置變量<?php $pageName = "index"; ?> <?php $pageName = "index"; ?>在索引頁面上,類似地<?php $pageName = "contact"; ?> <?php $pageName = "contact"; ?>在聯系我們頁面

然后調用 header.php (即導航代碼在 header.php) <?php include('header.php'); > <?php include('header.php'); >

在 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>

希望這會有所幫助,因為我花了幾天時間讓 jquery 工作但失敗了,

如果有人願意解釋包含 header.php 然后頁面加載時究竟是什么問題......為什么 jquery 無法將活動類添加到導航鏈接......?

對於 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>

使用 bootstrap 4,我錯過了我還需要添加的文檔

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

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

很多人需要一個 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');
            }
        }
    })
})

更改您的 class

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

並添加您的.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