Bootstrap CSS主动导航 [英] Bootstrap CSS Active Navigation

查看:110
本文介绍了Bootstrap CSS主动导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bootstrap网站上,subnav与部分匹配,并更改背景颜色,或滚动到部分。我想创建我自己的菜单没有所有的背景颜色和一切,但是,我改变了我的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 class="active"><a href="#">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 .active > a, .menu .active > a:hover {color:#F95700;}

jQuery,bootstrap.js和bootstrap.css都正确链接。我必须添加一些额外的jQuery或者我缺少一些CSS,以获得活跃的切换,像他们的网站上的subnav菜单。

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中:

$('.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆