点击更改图标(切换)

我在jquery中有一个简单的脚本,当点击

时切换一个div(显示和隐藏)(我正在使用bootstrap)。

HTML:

 

Advanced search

This is the advance search

JS:

 $('#click_advance').click(function(){ $('#display_advance').toggle('1000'); $(this).html(' Advanced search'); 

});

因此,当我第一次点击图标时,图标从下往上变化,但显然当我再次点击“click_advance”时,图标不会改变回来。 所以我想要像展示和隐藏一样的切换效果; 但是我对如何使用图标做了很多事情。

而不是每次都覆盖html,只需切换类。

 $('#click_advance').click(function() { $('#display_advance').toggle('1000'); $("i", this).toggleClass("icon-circle-arrow-up icon-circle-arrow-down"); }); 

试试这个:

 $('#click_advance').click(function(){ $('#display_advance').toggle('1000'); icon = $(this).find("i"); icon.hasClass("icon-circle-arrow-down"){ icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down"); }else{ icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up"); } }) 

甚至更好,凯文说:

 $('#click_advance').click(function(){ $('#display_advance').toggle('1000'); icon = $(this).find("i"); icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down") }) 

如果.toggle不工作,我会做下一个:

 var flag = false; $('#click_advance').click(function(){ if( flag == false){ $('#display_advance').show('1000'); // Add more code flag = true; } else{ $('#display_advance').hide('1000'); // Add more code flag = false; } } 

这是一个更多的代码,但它的工作原理

如果您的图标基于块中的文本(连字)而不是块的类,则以下内容将起作用。 此示例使用Google Material Icons’+’和’ – ‘图标作为MaterialiseCSS的一部分。

 add $('.btn-class').on('click',function(){ if ($(this).find('i').text() == 'add'){ $(this).find('i').text('remove'); } else { $(this).find('i').text('add'); } 

它也适用于JQuery post 1.9,其中不推荐使用函数切换。

这是一种非常简单的方法

  $(function () { $(".glyphicon").unbind('click'); $(".glyphicon").click(function (e) { $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down"); }); 

希望这会有所帮助:D