我的active
类没有在<li>
之间切换,我不确定为什么。这是我的代码段:
.active {
background: #ef5b00;
color: #FFF;
}
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="master.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="wrapper">
<nav class="sidebar" id="sidebar-id">
<div class="sidebar-header">
<h3>Test</h3>
</div>
<!-- end sidebar header -->
<ul class="list-unstyled nav components">
<li class="active"><a href="#"><i class="glyphicon glyphicon-home"></i>Home</a></li>
<li><a href="#"><i class="glyphicon glyphicon-briefcase"></i>About</a></li>
<li><a href="#"><i class="glyphicon glyphicon-duplicate"></i> Pages</a></li>
<li><a href="#"><i class="glyphicon glyphicon-link"></i>Portfolio</a></li>
<li><a href="#"><i class="glyphicon glyphicon-send"></i>Contact</a></li>
</ul>
<!-- end sidebar links -->
</nav>
<!-- end sidebar -->
<script type="text/javascript">
$(".nav li").click(function() {
if ($(".nav li").hasClass("active")) {
$(this).removeClass("active");
} else {
$(this).addClass("active");
}
});
</script>
</body>
如您所见,单击的链接确实带有灰色阴影,但是'Orange'
active
类不会被传输。我认为我的
css
是不正确的,因为我确实认为这是现在由bootstarp管理的,但是我不确定自己在做什么错。 最佳答案
这是因为活动类在单击时未移至其他任何li(添加jQuery代码)
像下面这样:
$(document).ready(function(){
$('li').click(function(){
$('li').removeClass('active');
$(this).addClass('active');
$(this).find('a').blur(); // to stop link hover CSS effect imidiattly (first-time)
});
});
.sidebar ul li.active {
background: #ef5b00;
color: #FFF;
}
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="master.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="wrapper">
<nav class="sidebar" id="sidebar-id">
<div class="sidebar-header">
<h3>Test</h3>
</div>
<!-- end sidebar header -->
<ul class="list-unstyled nav components">
<li class="active"><a href="#"><i class="glyphicon glyphicon-home"></i>Home</a></li>
<li><a href="#"><i class="glyphicon glyphicon-briefcase"></i>About</a></li>
<li><a href="#"><i class="glyphicon glyphicon-duplicate"></i> Pages</a></li>
<li><a href="#"><i class="glyphicon glyphicon-link"></i>Portfolio</a></li>
<li><a href="#"><i class="glyphicon glyphicon-send"></i>Contact</a></li>
</ul>
<!-- end sidebar links -->
</nav>
<!-- end sidebar -->
</body>