我使用twitter bootstrap nav-pills并更改了背景颜色。当页面首次加载时,它会输出正确的背景颜色。但是在我的javascript文件更改之后,li是“活跃的”#39;它似乎没有回应css。
HTML
<ul class="nav nav-pills">
<li id="About" role="presentation" class="active"><a href="#">About</a></li>
<li id="Animals" role="presentation"><a href="#">Animals</a></li>
<li id="Adoptly" role="presentation"><a href="#">Adoptly</a></li>
<li id="Blog" role="presentation"><a href="#">Blog</a></li>
<li id="Events" role="presentation"><a href="#">Events</a></li>
</ul>
CSS
.nav-pills>li.active>a, .nav-pills>li.active>a:focus, .nav-pills>li.active>a:hover {
color:white !important;
background-color:#FF4571 !important;
}
的Javascript
function checkWidth() {
var windowsize = $(window).width();
var current = document.getElementsByClassName('active');
var displayText = current[0].textContent;
if (windowsize > 425) {
//if the window is greater than 440px wide then turn on jScrollPane..
$( "#navigation" ).empty();
$( "#navigation" ).html(pillsHTML);
checkActive(displayText,true);
}
else
{
$( "#navigation" ).empty();
$( "#navigation" ).html(listHTML);
checkActive(displayText,false);
}
}
function checkActive(currentTab, bool){
console.log(bool);
if(bool)
{
$('li').removeClass('active');
var element = document.getElementById(currentTab);
$(element).addClass('active');
}
else
{
$('.list-group-item').removeClass('active');
var element = document.getElementById(currentTab);
$(element).addClass('active');
}
}
checkWidth();
// Bind event listener
$( window ).resize(checkWidth);
$('#navigation').on('click','li',function(e){
var previous = $(this).closest(".nav").children(".active");
previous.removeClass('active'); // previous list-item
$(e.target).addClass('active'); // activated list-item
});
答案 0 :(得分:0)
这里有两件事:HTML中的ul
标记没有id="navigation"
,而e.target
的结果是<a />
标记,而不是他们的父级<li />
,您的样式已设置好。
添加id="navigation"
并将addClass行切换为:
$(e.target).closest('li').addClass('active');
你应该好好去。
修改:这里的Codepen也只是为了说明:http://codepen.io/anon/pen/VaOmbz