简体   繁体   English

在飞行中使用jquery更改fontawesome图标

[英]Change fontawesome icons using jquery on the fly

I have created a navigational menu with some of them having submenus. 我创建了一个navigational menu ,其中一些navigational menu有子菜单。 I want the menuitem with fa-chevron-down (down arrow icon) to change to change to fa-chevron-up (up arrow icon) when user clicks on that menu item and changes back when user clicks anywhere else. 当用户点击该菜单项时,我希望将带有fa-chevron-down (向下箭头图标)的menuitem更改为fa-chevron-up (向上箭头图标),并在用户点击其他任何位置时进行更改。 Plus i also have two request, 另外我还有两个请求,

1) Since i am very new to jquery, the jquery code that i wrote seems to do the trick but is there a better way? 1)因为我对jquery很新,我写的jquery代码似乎可以解决问题,但有更好的方法吗? (notice when one menu item is clicked twice the sliding takes place twice. ITS ANNOYING) (注意当单击一个菜单项两次时,滑动发生两次。ITS ANNOYING)

2) When user resizes the window the html elements doesnot stays in place and scatters. 2)当用户调整窗口大小时,html元素不会保留在原位并散布。

Thanks in advance. 提前致谢。

jsfiddle demo jsfiddle演示

UPDATE : Thanks for solving my problem. 更新:感谢您解决我的问题。 I refined my problem further and it is working perfectly. 我进一步完善了我的问题,它运作得很好。 Here is the final** JSFIDDLE ** 这是最终的** JSFIDDLE **

For changing the icon you can easily do something like this in your click event: 要更改图标,您可以在点击事件中轻松执行以下操作:

$(this).find($(".fa")).removeClass('fa-chevron-down').addClass('fa-chevron-up');

for More take a look at jsfiddle example: 更多看看jsfiddle的例子:

jsfiddle example jsfiddle的例子

I think there is no need for changing the class. 我认为没有必要改变课程。

If you only want to change the fa-chevron-down to fa-chevron-up icon, instead of switching the classes, just use toggleClass for fa-rotate-180 . 如果您只想将fa-chevron-down更改为fa-chevron-up图标,而不是切换类,只需使用toggleClass for fa-rotate-180 fa-rotate-180 will rotate your icon and it might solve your purpose. fa-rotate-180将旋转您的图标,它可能会解决您的目的。 No need for adding/removing individual classes. 无需添加/删除单个类。

Let's say: 让我们说:

$('selector').click(function(){
    $('menu-selector').toggleClass('fa-rotate-180');    
});

It's just a sample. 这只是一个样本。 You can work around it. 你可以解决它。

Font Awesome v5 has changed things quite a bit. Font Awesome v5改变了很多东西。

This is the code I used to get a plus/minus collapse button working with Bootstrap, JQuery and FontAwesome. 这是我用来获取使用Bootstrap,JQuery和FontAwesome的加/减折叠按钮的代码。

HTML: HTML:

<a class="btn btn-collapse" id="btn-collapse" data-toggle="collapse" data-target="#collapse-section"><i class="fas fa-minus"></i></a>

JQuery script: JQuery脚本:

$("#btn-collapse").click(function() {
    if ($(this).hasClass('collapsed')) {
        $(this).find('svg').attr('data-icon', 'minus');
    } else {
        $(this).find('svg').attr('data-icon', 'plus');
    }
});

You should be able to substitute plus/minus for chevron up and down. 你应该能够上下加上/减去chevron的加/减。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM