单击更改li元素的背景 [英] Change background on li element on click
问题描述
我想做的是当用户单击链接时,背景应更改为表明用户单击了哪个链接".我正在尝试使用jQuery:
The thing I want to do is when a user clicks on a link, the background should change to Indicate which Link the user has clicked on. I'm trying to do this with jQuery:
$('.menuLink').click(function() {
var img = $(this).find('img');
var id = $(this).attr('id');
$("#" + id).addClass('activeLink');
console.log(id);
});
.menuLinks li {
color: #ffffff;
float: left;
margin-left: 2px;
width: 115px;
height: 60px;
background-color: #004f80;
text-align: center;
font-size: 13px;
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
.menuLinks li:hover {
background-color: #006eb3;
cursor: pointer;
}
.menuLinks li a {
color: #fff;
}
.activeLink {
color: #004f80;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menuLinks">
<li class="menuLink" id="tillstandshavare">Link1</li>
<li class="menuLink" id="stationer">Lnk2</li>
<li class="menuLink" id="formular">Link3</li>
<li class="menuLink" id="fragor">Link4</li>
<li class="menuLink" id="installningar">Link5</li>
</ul>
如您所见,我正在附加activeLink类.但是背景永远不会改变.我认为这是因为menuLinks没有被覆盖.
As you can see, I'm attaching the activeLink class. But the background are never changed. I think this is because of menuLinks is not overrided.
推荐答案
问题是因为.activeLink
类不够具体,无法覆盖默认的.menuLink li
样式.您需要使其更具体.还要注意,您可以使用this
来引用所单击的元素,而不是手动构建id选择器字符串.试试这个:
The issue is because the .activeLink
class is not specific enough for it to override the default .menuLink li
styling. You need to make it more specific. Also note that you can use this
to reference the clicked element instead of building the id selector string manually. Try this:
$('.menuLink').click(function() {
$(this).addClass('activeLink');
});
.menuLinks li {
color: #ffffff;
float: left;
margin-left: 2px;
width: 115px;
height: 60px;
background-color: #004f80;
text-align: center;
font-size: 13px;
font-weight: normal;
font-style: normal;
font-stretch: normal;
}
.menuLinks li:hover {
background-color: #006eb3;
cursor: pointer;
}
.menuLinks li a {
color: #fff;
}
.menuLinks li.activeLink {
color: #004f80;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menuLinks">
<li class="menuLink" id="tillstandshavare">Link1</li>
<li class="menuLink" id="stationer">Lnk2</li>
<li class="menuLink" id="formular">Link3</li>
<li class="menuLink" id="fragor">Link4</li>
<li class="menuLink" id="installningar">Link5</li>
</ul>
这篇关于单击更改li元素的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!