How to determine the current state of jQuery toggl

2019-05-07 08:38发布

I'm showing and hiding divs when another div is clicked on. I need to be able to determine if a particular div is either shown or hidden.

Ultimately what I'm trying to do is, when a certain div is clicked on, all other "show/hide" divs should be hidden and then determine if the clicked-div's related div is showing, if so hide it, otherwise show it.

I also need to add/remove a css class (for background color) to the shown/hidden div based on its toggle state.

Here's the jQuery code I'm using to toggle the show/hide state of the divs:

$('#movieListTable').on('click', 'div.vitalsTable', function (e) {

    // Don't do anything if the Edit button or Delete checkbox is clicked
    if (event.target.className !== 'btnEditMovie' && event.target.className !== 'chkDeleteMovie') {

        $(this).parent().parent().find('div.detailsTable').toggle('blind','easeInOutQuart', 300);
    }
});

The weird - and frustrating - thing is, everything I've read, including answers here at SO, indicate I should just be able to either check for the display state ("none") or the visible property, but checking in the console neither of those are being set on the div that is being shown/hidden.

I created a jsFiddle for you to mess with.

The jQuery documentation on toggle() discusses, about 3/4 of the way down the page, a boolean parameter "showOrHide" for one of the ways to use toggle(), but I haven't been able to figure out how to use that myself...

3条回答
We Are One
2楼-- · 2019-05-07 09:00
$('.elem').slideToggle('fast', function() {
    alert($(this).is(':visible'));
});
查看更多
beautiful°
3楼-- · 2019-05-07 09:03
var className = $(el).attr("class"); 

Can retrieve current class from there on logic can take over test and modify the element:

  • if(className == "yourCss")
  • el.addClass("YourCSS");
  • el.removeClass("YourCSS");

I still believe jvnill's answer is efficient one, unless one has to test multiple class cases.

toggle(): Just toggle of between hide() and show() for the selected elements, by changing the CSS display property.

Note: As a class is added to the element, class attribute(list) of the element gets appended with it, unless removed by the .removeClass() invocation.

查看更多
闹够了就滚
4楼-- · 2019-05-07 09:08

you can use $(div).is(':visible')

查看更多
登录 后发表回答