简体   繁体   English

使用slideToggle添加/删除类

[英]Adding / removing class with slideToggle

When clicking on a heading a menu (ul/li) is slided down / up with slideToggle. 单击标题时,使用slideToggle向下/向上滑动菜单(ul / li)。 As background of the heading I have an arrow pointing down if menu isn't visible, up otherwise (I have two classes, 'arrow-up' and 'arrow-down' for the background). 作为标题的背景我有一个箭头指向下方如果菜单不可见,否则(我有两个类,'箭头向上'和'向下箭头'为背景)。

Below is what I've tried but it doesn't work. 以下是我尝试过的但它不起作用。 What would be a good solution? 什么是一个好的解决方案?

$j('h3.sub-menu-dropdown-btn').click(function(){

    if ($j('ul').is(":visible")) {
        $j(this).removeClass('arrow-up');
        $j(this).addClass('arrow-down');
    } else {
        $j(this).removeClass('arrow-down');
        $j(this).addClass('arrow-up');
    }

    $j('.sub-menu-dropdown').slideToggle('fast');

});

You could try that and see if it fits your needs: 你可以尝试一下,看看它是否符合你的需求:

$j('h3.sub-menu-dropdown-btn').click(function(){
    var $self = $j(this);
    $j('.sub-menu-dropdown').slideToggle('fast', function(){
        $self.toggleClass('arrow-up arrow-down');
    });
});

Try using hasClass(): https://api.jquery.com/hasClass/ 尝试使用hasClass(): https ://api.jquery.com/hasClass/

$j('h3.sub-menu-dropdown-btn').click(function(){

    if ($j('ul').hasClass('arrow-up')) {
        $j(this).removeClass('arrow-up');
        $j(this).addClass('arrow-down');
    } else {
        $j(this).removeClass('arrow-down');
        $j(this).addClass('arrow-up');
    }

    $j('.sub-menu-dropdown').slideToggle('fast');

});

Also, and I cannot verify this without seeing the html markup, the selector $j('ul') may be too general. 另外,我无法在没有看到html标记的情况下验证这一点,选择器$j('ul')可能过于笼统。

你需要像这样使用:

if($j("ul").is(":visible")==true){

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

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