jquery - 如何在 slideToggle 上添加/删除类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4065654/
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-08-26 16:36:47  来源:igfitidea点击:

jquery - how to add/remove class on slideToggle?

jqueryslide

提问by MEM

I would like to each time the div expands, to add the class 'selecionado' once the expansion is finished. When the contraction is done (the slideUp part) I would like to remove this class.

我想每次 div 扩展时,在扩展完成后添加类“selecionado”。当收缩完成(slideUp 部分)我想删除这个类。

Can I have a help here please?

我可以在这里帮忙吗?

$('#btCategoriaA').click(function()
{
  $('#listaCategoriaA').slideToggle('slow', function() {
   $('#btCategoriaA').addClass('selecionado');
  });
});

Thanks in advance, MEM

提前致谢,MEM

回答by Nick Craver

You can toggle the class using .toggleClass()based on if the element .is():visibleafter the animation, like this:

您可以.toggleClass()根据动画后的元素使用if切换类,如下所示:.is():visible

$('#btCategoriaA').click(function() {
  $('#listaCategoriaA').slideToggle('slow', function() {
    $('#btCategoriaA').toggleClass('selecionado', $(this).is(':visible'));
  });
});