Bootstrap CSS 主动导航 [英] Bootstrap CSS Active Navigation
问题描述
在 Bootstrap 网站上,子导航与各部分匹配,并在您或滚动到该部分时更改背景颜色.我想创建自己的菜单,但没有所有背景颜色和所有内容,但是,我将 CSS 更改为类似的,但是当我向下滚动或单击菜单项时,活动类不会切换.不知道我做错了什么.
On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the background colors and everything, however, I changed my CSS to be similar but when I scroll down or click on the menu item the active class does not switch. Not sure what I'm doing wrong.
HTML:
<ul class="menu">
<li><a href="#" aria-current="page">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
CSS:
.menu {
list-style:none;
}
.menu > li {
float: left;
}
.menu > li > a {
color: #555;
float: none;
padding: 10px 16px 11px;
display: block;
}
.menu > li > a:hover {
color: #F95700;
}
.menu a[aria-current="page"],
.menu a[aria-current="page"]:hover {
color:#F95700;
}
我检查了文件;jQuery、bootstrap.js 和 bootstrap.css 都正确链接.我是否必须添加一些额外的 jQuery 或者我是否缺少一些 CSS 才能像他们网站上的子导航菜单一样激活切换?
I checked the files; jQuery, bootstrap.js and bootstrap.css are all linked properly. Do I have to add some additional jQuery in or am I missing some CSS to get the active to switch like the subnav menu on their site?
推荐答案
为了切换类,需要执行一些JavaScript.
In order to switch the class, you need to perform some JavaScript.
在 jQuery 中:
In jQuery:
$('.menu li a').click(function(e) {
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
在 JavaScript 中:
In JavaScript:
var menu = document.querySelector('.menu');
var anchors = menu.getElementsByTagName('a');
for (var i = 0; i < anchors.length; i += 1) {
anchors[i].addEventListener('click', function() { clickHandler(anchors[i]) }, false);
}
function clickHandler(anchor) {
var hasClass = anchor.getAttribute('class');
if (hasClass !== 'active') {
anchor.setAttribute('class', 'active');
}
}
我希望这会有所帮助.
这篇关于Bootstrap CSS 主动导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!