[英]Is possible to toggle between 2 FontAwesome 5 icons (regular and solid) using jQuery
I was trying to toggle two classes simultaneously one fas
and far
and another border-heart and selected heart. 我试图切换两个班同时一个
fas
和far
和其他边境心脏和心脏选择。 The code results in the display of another solid heart along with the regular one. 该代码将显示另一颗坚实的心脏以及正常的心脏。
var w=1 $('.heart').on('click',function() { if(w == 1) { $('.heart').removeClass('far fa-heart').addClass('fas fa-heart'); $('.heart').removeClass('border-heart').addClass('selected-heart'); } else { $('.heart').removeClass('fas fa-heart').addClass('far fa-heart'); $('.heart').removeClass('selected-heart').addClass('border-heart'); } w=1-w; }); /*I want to toggle the regular heart icon with solid on click and increase its size by 1 px using selected-heart class and removing border-heart*/
.border-heart{ color: red; font-size: 21px; } .selected-heart{ color: red; font-size: 22px; }
<link href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="heart"><i class="far fa-heart border-heart"></i></div>
You have to target the <i>
within .heart
using .find()
... Then simply use the .toggleClass()
method on both .far
and .fas
classes (and the 2 custom classes you have for font-size change). 您必须使用
.find()
在.heart
内定位<i>
...然后只需在.far
和.fas
类(以及用于更改字体大小的2个自定义类.toggleClass()
上使用.toggleClass()
方法。
;) ;)
$('.heart').on('click',function() { $(this).find("i").toggleClass("far fas selected-heart border-heart"); });
.border-heart{ color: red; font-size: 21px; } .selected-heart{ color: red; font-size: 22px; }
<link href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="heart"><i class="far fa-heart border-heart"></i></div>
I think this is a quick fix. 我认为这是一个快速解决方案。 It looks like you're trying to toggle between two classes, however, you have selected the parent of the item you actually want.
看起来您正在尝试在两个类之间切换,但是,您已经选择了想要的项目的父项。 You are selecting the
.heart
div, but you actually want to be selecting the i
element within. 您正在选择
.heart
div,但实际上您想在其中选择i
元素。 You should modify your jquery to the following; 您应该将jquery修改为以下内容;
var w=1
$('.heart').on('click',function() {
if(w == 1) {
//standard CSS selector selecting the child i element from the .heart element
$('.heart i').removeClass('fas fa-heart').addClass('fa fa-heart');
}
else {
$('.heart i').removeClass('fa fa-heart').addClass('fas fa-heart');
}
w=w-1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.