假设我有以下css:
<style>
.liked {
color: #600;
}
.not-liked {
color: #aaa;
}
</style>
假设我有这个:<i class = 'fa fa-heart-o not-liked' id = "banner"></i>
在我的jQuery中,如果我将类从not-liked
交换到liked
,那么也可以在同一个类中将fa- can o交换为fa-can吗?
所以我尽量避免这样做:
function() {
$("#banner").removeClass('not-liked');
$("#banner").removeClass('fa-heart-o');
$("#banner").addClass('liked');
$("#banner").addClass('fa-heart');
}
基本上切换颜色和图标如下:
function() {
$("#banner").removeClass('not-liked');
$("#banner").addClass('liked');
}
发布于 2016-03-14 05:05:12
FontAwesome图标可以通过它们的Unicode标识符访问。实际上,样式表提供的所有预定义类都是使用::before
伪元素选择器和content
以相同的方式创建的。
我们可以看到fa-heart
是f004
,fa-heart-o
是f08a
。
如果您想减少HTML和JavaScript的类列表开销,只需调整自己的类来表示所需的内容。
$('.toggle').on('click', function () {
$(this).toggleClass('not-liked liked');
});
$('.once').on('click', function () {
$(this).removeClass('not-liked').addClass('liked');
});
.liked::before {
color: #600;
content: '\f004';
}
.not-liked::before {
color: #aaa;
content: '\f08a';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<span class='toggle fa not-liked'></span>
<span class='once fa not-liked'></span>
发布于 2016-03-14 07:24:52
尝试使用下面的代码,您可以继续使用jquery删除和添加类。
$( "i#banner" ).click(function() {
$(this).toggleClass( "fa-heart-o not-liked fa-heart liked" );
});
.liked {
color: #600;
}
.not-liked {
color: #aaa;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<i class = 'fa fa-heart-o not-liked' id="banner"></i>
<i class = 'fa fa-heart-o not-liked' id="banner"></i>
<i class = 'fa fa-heart-o not-liked' id="banner"></i>
发布于 2016-03-14 04:53:06
<i class = 'fa fa-heart-o not-liked' id = "#banner"></i>
在上面提到的代码中,请确保,
id = "banner" instead of id = "#banner"
然后您可以继续使用jquery删除和添加类;您的解决方案工作得很好,或者我更喜欢@Russel提供的解决方案。
https://stackoverflow.com/questions/35979582
复制相似问题