点击li
锚点后,我想更改背景颜色:
<div class="text-center row">
<ul class="col-md-12 secondNav">
<li class="navbar-brand nav-item" style="margin-right: 9%">
<a href="#" ><strong>INICIO</strong> </a>
</li>
<li class="navbar-brand nav-item" >
<a href="#"><strong>COMPARAR</strong></a>
</li>
</ul>
</div>
答案 0 :(得分:2)
您可以使用jquery更改li
背景。这是代码:
$(document).ready(function(){
$('.nav-item').click(function(e){
$(e.target).css('backgroundColor', 'red');
});
});
答案 1 :(得分:1)
因此,尽管我不一定推荐此解决方案。实际上,无需使用javascript就可以做到这一点!看看这个例子:https://jsfiddle.net/age5zdkb/2/
<div class="text-center row">
<ul class="col-md-12 secondNav">
<a href="#" >
<li class="navbar-brand nav-item" style="margin-right: 9%">
<input type="checkbox" id="demo"/>
<label for="demo"><strong>INICIO</strong></label>
</li>
</a>
<a href="#" >
<li class="navbar-brand nav-item" >
<input type="checkbox" id="demo1"/>
<label for="demo1"><strong>COMPARAR</strong></label>
</li>
</a>
</ul>
</div>
label {
display: block;
}
input[type="checkbox"] {
display:none;
}
#demo:checked + label, #demo1:checked + label {
background: pink;
color: white;
}
答案 2 :(得分:0)
这是在没有任何依赖的情况下进行操作的方法。
const listItems = document.querySelectorAll('.navbar-brand');
listItems.forEach(li => {
li.addEventListener('click', () => {
li.classList.toggle('alt-background');
});
});
.alt-background {
background-color: lightgray;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="text-center row">
<ul class="col-md-12 secondNav">
<li class="navbar-brand nav-item" style="margin-right: 9%">
<a href="#" ><strong>INICIO</strong> </a>
</li>
<li class="navbar-brand nav-item" >
<a href="#"><strong>COMPARAR</strong></a>
</li>
</ul>
</div>
答案 3 :(得分:0)
在CSS中单击导航项时,可以使用jquery添加活动类,为活动项添加背景颜色
https://jsfiddle.net/binoy/g6e1bykx/3/
In JS
$(document).ready(function(){
$('.nav-item').click(function(e){
$('.secondNav .nav-item').removeClass('active');
$(this).addClass('active');
});
});
In CSS
.secondNav .nav-item.active {
background-color: red;
}