我有一个简单的导航栏,试图将其单击时使背景变为绿色。但是,它似乎不起作用。
当我将鼠标悬停在链接上时,背景变为绿色并且工作正常。但是,我无法做到这一点,因此,当我单击链接时,背景保持绿色,如果单击另一个链接,则新的活动对象变为绿色,而先前的活动对象变为白色。
$(".sidebar ul li").on("click", function() {
$(".sidebar ul li").removeClass("active");
$(this).addClass("active");
});
.sidebar {
margin: 0;
padding: 0;
width: 276px;
background-color: #ffffff;
position: fixed;
height: 100%;
}
.sidebar a {
display: block;
color: #444444;
padding: 4px 0px 4px 15px;
text-decoration: none;
font-size: 14px;
}
.sidebar a:hover {
border: 1px;
border-collapse: #1aa322;
background-color: #1aa322;
color: #ffffff;
}
.sidebar li.active {
color: #ffffff;
background-color: #1aa322;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
<div id="logo">
<IMG SRC="img/logo.png" ALT="Logo">
</div>
<div>
<div id="menu-header">
<p>INTRODUCTION</p>
</div>
</div>
<ul>
<li class="" id=menu>
<a href="#Welcome">Welcome</a>
</li>
<li class="" id=menu>
<a href="#Authentication">Authentication</a>
</li>
<li class="" id=menu>
<a href="#Pagination">Pagination</a>
</li>
<li class="" id=menu>
<a href="#Errors">Errors</a>
</li>
</ul>
最佳答案
将jQuery链接添加到您的代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".sidebar ul li").on("click", function () {
$(".sidebar ul li").removeClass("active");
$(this).addClass("active");
});
.sidebar {
margin: 0;
padding: 0;
width: 276px;
background-color: #ffffff;
position: fixed;
height: 100%;
}
.sidebar a {
display: block;
color: #444444;
padding: 4px 0px 4px 15px;
text-decoration: none;
font-size: 14px;
}
.sidebar a:hover {
border: 1px;
border-collapse: #1aa322;
background-color: #1aa322;
color: #ffffff;
}
.sidebar li.active {
color: #ffffff;
background-color: #1aa322;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sidebar">
<div id="logo">
<IMG SRC="img/logo.png" ALT="Logo">
</div>
<div>
<div id="menu-header">
<p>INTRODUCTION</p>
</div>
</div>
<ul>
<li class="" id=menu>
<a href="#Welcome">Welcome</a>
</li>
<li class="" id=menu>
<a href="#Authentication">Authentication</a>
</li>
<li class="" id=menu>
<a href="#Pagination">Pagination</a>
</li>
<li class="" id=menu>
<a href="#Errors">Errors</a>
</li>
</ul>
关于javascript - 单击时导航栏不会更新为事件状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56288754/