javascript 使用 FontAwesome 5.0 SVG Framework 时在图标之间切换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46210501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:32:05  来源:igfitidea点击:

Switch between icons when using FontAwesome 5.0 SVG Framework

javascripthtmlsvgfont-awesomefont-awesome-5

提问by Monbrey

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

我希望能够在使用新的 FontAwesome SVG 框架时在 Javascript 中的图标之间切换。

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.

以前在旧的 WebFont 方法中,这是通过切换或更改标签上的类来实现的,但是由于这些现在在源代码中呈现为 SVG,这不再有效。

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?

有没有办法做到这一点,而无需在源代码中呈现两个 SVG 图标并使用额外的类/CSS 来切换显示?

回答by Pascal

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.

Font Awesome 5.0.0 刚刚发布,从 4.7 到 5.0 的迁移破坏了我的 javascript/jquery,当用户点击它时将“fa-star-o”图标更改为“fa-star”。

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

我设法修复了它,所以我想与您分享这两个技巧:

The icon in HTML:

HTML 中的图标:

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

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

1) 使用 jQuery 更改图标(从“星”到“闹钟”,反之亦然):

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'):

2) 使用 jQuery 更改图标样式(从 'fas' 到 '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.

希望能帮助任何有同样问题的人。

回答by Steven

Verified with FA 5.0.2

已通过 FA 5.0.2 验证

I modified the original documentation found on Font-Awesome's website here. The selector on their website wasn't selecting the proper element, so we need to modify the attribute.

我修改的字体,真棒的网站上找到了原始的文档在这里。他们网站上的选择器没有选择正确的元素,所以我们需要修改属性。

HTML

HTML

<div class='icon'><i class='far fa-minus-square'></i></div>

The class of the div doesn't really matter so much as we can change it. Looking at the javascript, we are using the element to find the svg and specifically, we are looking for the data-icon attribute. Once we know the data attribute, we can change it every time it is clicked.

div 的类并不重要,因为我们可以更改它。查看 javascript,我们正在使用该元素来查找 svg,具体而言,我们正在查找 data-icon 属性。一旦我们知道了数据属性,我们就可以在每次点击时更改它。

So in this case, it starts off with the minus-square. If the icon is the minus-square, it changes it to the plus-square. If it is not the plus-square, it will change it to the minus-square.

所以在这种情况下,它从负平方开始。如果图标是减号方块,它会将其更改为加号方块。如果不是正方,则将其更改为负方。

JQuery

查询

  document.addEventListener('DOMContentLoaded', function () {
    $('.icon').on('click', function () {
      if ($(this).find('svg').attr('data-icon') == 'minus-square' ) {
        $(this).find('svg').attr('data-icon', 'plus-square');
      } else {
        $(this).find('svg').attr('data-icon', 'minus-square');
      };
    });
  });

回答by nicozica

Assuming you are using the recommended method with the fontawesome.jssheet, I found this on the official documentation:

假设您在fontawesome.js表中使用推荐的方法,我在官方文档中找到了这个:

Changing icons by changing class:

通过更改类来更改图标:

<button>Open up <i class="fa fa-angle-right"></i></button>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    $('button').on('click', function () {
      $(this)
        .find('[data-fa-i2svg]')
        .toggleClass('fa-angle-down')
        .toggleClass('fa-angle-right');
    });
  });
</script>

回答by csb

I had the same problem as well, and I found (after scrolling right to the very end) that the FontAwesome websitestates the following:

我也遇到了同样的问题,我发现(在向右滚动到最后之后)FontAwesome 网站声明如下:

Nest <svg>tags instead of replacing

There may be some cases where the replacement of the <i>tag is just not working out like you need it to.

You can configure Font Awesome to nest the within the tag.

嵌套<svg>标签而不是替换

在某些情况下,<i>标签的替换可能无法按照您的需要进行。

您可以配置 Font Awesome 将 嵌套在标签内。

To do so, just the FontAwesomeConfigobject and set autoReplaceSvg: 'nest'.

为此,只需FontAwesomeConfigobject 和 set autoReplaceSvg: 'nest'

<script>
    FontAwesomeConfig = { autoReplaceSvg: 'nest' }
</script>

回答by Blitzlord

Didn't find any documentation about this. As it's not offically released yet, you can use this workaround (jQuery):

没有找到任何关于此的文档。由于尚未正式发布,您可以使用此解决方法 (jQuery):

$('svg.fa-toggle-off').replaceWith('<i class="fas fa-toggle-on"></i>');

回答by Mario Lurig

Verified with FA 5.0.0 using the recommended JS method for loading icons

使用 FA 5.0.0 验证,使用推荐的 JS 方法加载图标

HTML

HTML

<div id='icon'><i class='far fa-eye-slash'></i></div>

This is what the HTML code looks like once the page is rendered, prior to a click:

在单击之前呈现页面后,HTML 代码如下所示:

<div id="icon"><svg class="svg-inline--fa fa-eye-slash fa-w-18" aria-hidden="true" data-fa-processed="" data-prefix="far" data-icon="eye-slash" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M272.702 359.139c-80.483-9.011-136.212-86.886-116.93-167.042l116.93 167.042zM288 392c-102.556 0-192.092-54.701-240-136 21.755-36.917 52.1-68.342 88.344-91.658l-27.541-39.343C67.001 152.234 31.921 188.741 6.646 231.631a47.999 47.999 0 0 0 0 48.739C63.004 376.006 168.14 440 288 440a332.89 332.89 0 0 0 39.648-2.367l-32.021-45.744A284.16 284.16 0 0 1 288 392zm281.354-111.631c-33.232 56.394-83.421 101.742-143.554 129.492l48.116 68.74c3.801 5.429 2.48 12.912-2.949 16.712L450.23 509.83c-5.429 3.801-12.912 2.48-16.712-2.949L102.084 33.399c-3.801-5.429-2.48-12.912 2.949-16.712L125.77 2.17c5.429-3.801 12.912-2.48 16.712 2.949l55.526 79.325C226.612 76.343 256.808 72 288 72c119.86 0 224.996 63.994 281.354 159.631a48.002 48.002 0 0 1 0 48.738zM528 256c-44.157-74.933-123.677-127.27-216.162-135.007C302.042 131.078 296 144.83 296 160c0 30.928 25.072 56 56 56s56-25.072 56-56l-.001-.042c30.632 57.277 16.739 130.26-36.928 171.719l26.695 38.135C452.626 346.551 498.308 306.386 528 256z"></path></svg><!-- <i class="far fa-eye-slash"></i> --></div>

JQUERY (on click used)

JQUERY(点击使用)

$("#icon").click(function() {
  // Change the child svg attribute data-icon to the new icon (remove fa-)
  $("#icon > svg").attr('data-icon','eye');
});

This will change the icon from eye-slashto eye.

这会将图标从eye-slash更改为eye

Edit: Dec 20, 2017
As of Font Awesome 5.0.1, when using the Javascript version you can now add/remove classes as before, it just needs to be on the svgelement rather than the original element (assuming i).

编辑:2017 年 12 月 20 日
从 Font Awesome 5.0.1 开始,当使用 Javascript 版本时,您现在可以像以前一样添加/删除类,它只需要位于svg元素而不是原始元素上(假设i)。

Updated code:

更新代码:

$("#icon").click(function() {
  // Change the child svg attribute data-icon to the new icon (remove fa-)
  $("#icon > svg").addClass('fa-eye').removeClass('fa-eye-slash');
});

Also note that any applied idsor classesto the font awesome element will be brought over to the svg. Thus if you have <i id='eyecon' class='eyecon fa fa-eye'>then it will render the <svg id='eyecon' class='eyecon'>.

另请注意,任何应用于字体 awesome 元素的id都将被带到svg。因此,如果您有,<i id='eyecon' class='eyecon fa fa-eye'>那么它将呈现<svg id='eyecon' class='eyecon'>.

回答by Pawel

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

这是我发现最适合我的方法。我使用的是自托管 Fontawesome v5.7.1

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

HTML(注意两个图标,一个带有 .hidden 类)

<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

CSS

.hidden {
  display: none;
}

jQuery

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');
});

回答by Eonasdan

For a plain JS example (password reveal)

对于一个普通的 JS 示例(密码显示)

//event = mouse click
const passwordInput = event.currentTarget
    .closest('.input-group')
    .querySelector('input');
let icon = 'eye-slash';
let newType = 'text';

// type is text, set to password and change icon to eye
if (passwordInput.getAttribute('type') === 'text') {
    icon = 'eye';
    newType = 'password';
}
passwordInput.setAttribute('type', newType);
event.currentTarget
    .querySelector('svg')
    .setAttribute('data-icon', icon);