我试图在jQuery中切换图标的类名。
我正在使用字体很棒的库,它只替换了我班上的首字母"fa“,这是我的jsfiddle
$('[name="caret"]').click(function() {
$(this).toggleClass('fa fa-caret-up fa-1x');
});
JSFiddle
发布于 2015-12-02 08:29:46
它没有更改为fa-caret-up
,因为您还需要切换类fa
,这对于字体库来说是必需的,以实现它是一个图标。
所以就这么做吧
$('[name="caret"]').click(function() {
$(this).toggleClass('fa-caret-up fa-caret-down');
});
这将删除fa-caret-down
类并添加fa-caret-up
类。
更新Fiddle
发布于 2015-12-02 08:31:16
相反,只需使用这个:
$(this).toggleClass('fa-caret-up');
在css中,您可以看到类的顺序。一个是最后一个,它只是凌驾于上面的顺序。因此,将类fa-caret-up
切换到现有的类就足够了。
您可以看到下面的示例:
$('[name="caret"]').click(function () {
$(this).toggleClass('fa-caret-up');
});
body {
font-family: Arial;
}
.accordion {
border-top: 1px solid #c1c1c1;
}
.accordion dt {
border: 1px solid #c1c1c1;
border-top: 0px solid #c1c1c1;
margin: 0px;
padding: 10px 15px;
display: block;
cursor: pointer;
overflow: hidden;
}
.accordion dt span {
float: left;
font-weight: normal;
font-size: 17px;
}
.accordion dt .accordion_icon {
float: right;
}
.accordion dt.active {
background: #DBDBDB;
}
.accordion_content {
margin: 0;
padding: 15px;
border-left: 1px solid #c1c1c1;
border-right: 1px solid #c1c1c1;
border-bottom: 1px solid #c1c1c1;
}
<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" class="tablesorter table table-striped">
<thead>
<tr>
<th width="75px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
<th width="125px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
<th width="550px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
<th width="100px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
<th></th>
</tr>
</thead>
</table>
发布于 2015-12-02 08:36:20
$( "input[name='caret']" ).click(function() {
if ($(this).hasClass('fa-caret-up')) {
$(this).removeClass().addClass('fa fa-caret-down');
} else {
$(this).removeClass().addClass('fa fa-caret-up fa-1x');
}
});
https://stackoverflow.com/questions/34037854
复制相似问题