Hide a <div> set to display:block with jQuery

六月ゝ 毕业季﹏ 提交于 2021-01-29 04:30:57

问题


How can I check a div's visibility and, if the div is display:block;, hide it or, if the div is display:none;, leave it alone?

if(codition){
    $(".thanks").fadeIn('slow');
    $(".thanks").html(json[0]);
    $(".thanks").css('color','red');
}else{
    //HERE I want to check if the thanks div is display:block,hide it other wise ignore it    
    $(".errordiv").css('color','green');
    $(".errordiv").fadeIn('slow');
}

回答1:


It's probably not even worth checking if it's already visible, just call hide. eg.

$('.thanks').hide();



回答2:


Could you use :visible selector?

if($('div').is(':visible')){
//execute
}

Alternatively, I suppose you might be able to check its CSS value:

if($('div').css('display')=='block'){
//execute
}



回答3:


You can use the css method

if ($(".errordiv").css('display') == 'block') {
   //display is equal to block, use .hide();
}

Also, I'd like to note that if you only have one element, you're better off referring to it by an ID rather than a class. It's a micro optimization, but it's cleaner and faster.




回答4:


Consider this:

var elem1, elem2;

elem1 = $( '.thanks' )[0];
elem2 = $( 'errordiv' )[0];

if ( codition ) {
    $( elem1 ).html( json[0] ).addClass( 'class1' ).fadeIn( 'slow' );
} else {
    if ( $( elem1 ).is( ':visible' ) ) { $( elem1 ).hide(); }
    $( elem2 ).addClass( 'class2' ).fadeIn( 'slow' );
}

You have classes - "class1" and "class2" in my code, but you would of course have better names - to add the presentation to the elements.


Let me explain...

So, this:

var elem = $( '#test' )[0];

is equivalent to this:

var elem = document.getElementById( 'test' );

I use the $( '#...' )[0] notation as a shorthand for .getElementsById().




回答5:


I would imagine you could use toggle() to do this.

<div class='mixedDisplay' style='display: none;'>Hello</div>
<div class='mixedDisplay'>World</div>
$('.mixedDisplay').toggle();

http://jsfiddle.net/rlemon/Y8RwV/

I understand it's not exactly what you are looking for, but it might be useful.




回答6:


try this:

if ($('div.errordiv:visible').length) {
    ....
}


来源:https://stackoverflow.com/questions/8607836/hide-a-div-set-to-displayblock-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!