Switch between icons when using FontAwesome 5.0 SV

2020-02-21 02:45发布

I'm looking to be able to switch between icons in Javascript while using the new FontAwesome SVG framework.

Previously in the old WebFont method, this was achieved by toggling or changing the class on the tag, however as these are now rendered as SVG's in the source code this no longer works.

Is there a way to do this without needing to render both SVG icons in source code and using additional classes/CSS to toggle display?

8条回答
Rolldiameter
2楼-- · 2020-02-21 03:23

Font Awesome 5.0.0 has just been released and the migration from 4.7 to 5.0 wrecked up my javascript/jquery to change a "fa-star-o" icon to "fa-star" when the user clicks on it.

I managed to fix it so I wanted to share with you these two tips:

The icon in HTML:

<i class="foo fas fa-star"></i>

1) Change icon with jQuery (from "star" to "alarm-clock" and vice versa):

var icon = $('.foo');
var icon_fa_icon = icon.attr('data-icon');

if (icon_fa_icon === "alarm-clock") {
    icon.attr('data-icon', 'star');
} else {
    icon.attr('data-icon', 'alarm-clock');
}

2) Change icon-style with jQuery (from 'fas' to 'far'):

var icon = $('.foo');
var icon_fa_prefix = icon.attr('data-prefix');

if (icon_fa_prefix === 'fas') {
    icon.attr('data-prefix', 'far');

} else {
    icon.attr('data-prefix', 'fas');
}

Hope that helps anyone with the same issue.

查看更多
祖国的老花朵
3楼-- · 2020-02-21 03:26

This is what I found worked best for me. I was using self-hosted Fontawesome v5.7.1

HTML (note two icons, one with .hidden class)

<a id="delete_btn" href="#">
  <i class="icon fas fa-trash"></i>
  <i class="spinner fas fa-spinner fa-spin hidden"></i>
  <div class="caption">Delete</div>
</a>

CSS

.hidden {
  display: none;
}

jQuery

$('#delete_btn').click( function() {
  var fa_icon = $('#delete_btn .icon');
  var fa_spin = $('#delete_btn .spinner');
  fa_icon.addClass('hidden');
  fa_spin.removeClass('hidden');

  //do something

  fa_spin.addClass('hidden');
  fa_icon.removeClass('hidden');
});
查看更多
登录 后发表回答