[英]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 库,但这可能是另一篇文章。 我希望这会有所帮助和贡献。
这已经在 bootstrap 中实现,并在scrollspy部分下的文档中进行了简洁的解释。 链接到文档
修复活动状态切换的步骤:
position:relative
对于你的身体元素id="navbar"
添加到您的导航栏部分。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')
})
很多人需要一个 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.