我正在尝试根据从两个标题中单击的内容更改类。
如果单击第一个标题,我希望字体颜色更改为红色并用红色加下划线,这在当前类中带有底部边框。如果单击另一个标题,那么我希望该标题具有红色特征。未点击的将根据无高亮类保持灰色。
这是 JSFiddle:http://jsfiddle.net/7ok991am/1/我还举例说明了我要完成的工作。
HTML:
<div id="page_headings">
<h2 class="no_highlight">Heading One</h2>
<h2 class="no_highlight">Heading Two</h2>
</div>
CSS:
#page_headings{
overflow: hidden;
margin-bottom: 32px;
}
#page_headings h2{
float: left;
margin-right:24px;
font-size: 14px;
cursor:pointer;
}
#page_headings h2:hover{
font-weight: bold;
}
.red_highlight{
color:red;
border-bottom: 1px solid red;
}
.no_highlight{
color:#898989;
}
JS:
$('#page_headings').on('click', function(){
if($('#page_headings h2').hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$('#page_headings h2').addClass('no_highlight');
};
});
最佳答案
在@RDrazard 的基础上,我认为您希望他们在两者之间切换,对吗?
http://jsfiddle.net/7ok991am/3/
$('#page_headings h2').on('click', function(){
if($(this).hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$(this).addClass('no_highlight');
}
$(this).siblings('h2').addClass('no_highlight');
});
关于javascript - 如何使用 if 语句删除和添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25370189/