如何检查一个元素是否隐藏在 jQuery 中?

It is possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle().

How would you test if an element is visible or hidden?

转载于:https://stackoverflow.com/questions/178325/how-do-i-check-if-an-element-is-hidden-in-jquery

csdnceshi62
csdnceshi62 What is your definition of hidden?
大约 2 年之前 回复
weixin_41568208
北城已荒凉 This is related although a different question: stackoverflow.com/questions/17425543/…
4 年多之前 回复
csdnceshi70
笑故挽风 It's worth mentioning (even after all this time), that $(element).is(":visible") works for jQuery 1.4.4, but not for jQuery 1.3.2, under Internet Explorer 8. This can be tested using Tsvetomir Tsonev's helpful test snippet. Just remember to change the version of jQuery, to test under each one.
9 年多之前 回复

29个回答

Since the question refers to a single element, this code might be more suitable:

// Checks css for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible"); 

// The same works with hidden
$(element).is(":hidden"); 

Same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ

csdnceshi60
℡Wang Yan Changes in 1.12+ and 2.2.0+ and 3.0+ change the counts if multiple elements selected (see note at the bottom of this stackoverflow.com/a/17426800/125981)
3 年多之前 回复
csdnceshi79
python小菜 This doesn't work if it is hidden by a media query, how would I test for that?
4 年多之前 回复
weixin_41568126
乱世@小熊 Does not work on chrome though works flawlessly in firefox :( Had to do something like jQuery(textarea).parent().css('display') != 'none' instead of jQuery(textarea).parent().is(":visible")
接近 5 年之前 回复
csdnceshi69
YaoRaoLov Not working for element that have parent overflow: hidden;
5 年多之前 回复
weixin_41568184
叼花硬汉 This doesn't seem to return false if the element has opacity:0; set, any work around?
接近 6 年之前 回复
csdnceshi61
derek5. I don't see anything in the jQuery documentation about this being deprecated. I have also tested it with the latest jQuery and it does still work. Here: jsfiddle.net/F6atJ
大约 6 年之前 回复
csdnceshi78
程序go This doesn't work in the latest jquery. It's been deprecated. What's the best work around? (Why did they remove this...?)
6 年多之前 回复
csdnceshi57
perhaps? Also, I believe this works: $(selector).is('not(:hidden)')
6 年多之前 回复
csdnceshi54
hurriedly% I'm looking for a similar solution as well. So far I've been using $(element).css('display')=='none' to detect hidden elements.
6 年多之前 回复
csdnceshi65
larry*wei So, should we use .is(":invisible") for false? Or !$(element).is(":visible"), or just what?
6 年多之前 回复
csdnceshi76
斗士狗 I found this informative when looking up about :visible and :hidden. Essentially, it looks at the offsetHeight and offsetWidth allowing it to provide the best coverage (eg. you might have a class which has display:none; as a property and it will correctly report whether it is visible)
接近 7 年之前 回复
weixin_41568183
零零乙 How do you do the inverse of this?
接近 7 年之前 回复
weixin_41568208
北城已荒凉 - I'm pretty sure it's a GIVEN! (most of the time) that when you pull out the regexp knife that you'll take a perf. hit. The extra checks will be nil compared to the overhead/processing of regexp.
7 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 For other users wondering if this really does work in IE7, this might save you some time - it works, jquery 1.9.1: imgur.com/uKD4t8h
7 年多之前 回复
csdnceshi64
游.程 What does $(element).is(":visible") return, if the element is visible in terms of not having display:none or visibility:hidden, but the user scrolled down so he doesn't actually see it? Is there a simple way to check that?
7 年多之前 回复
weixin_41568174
from.. to check the parent's visibility, you can use $(element).parent().is(":visible"); I know this is bit old, but will useful for new search
接近 8 年之前 回复
csdnceshi67
bug^君 Tchalvak, you may feel something is right, but try to explain why. Double negation is confusing as opposed to simple statement, so $('selector').is(':shown'); is much clearer than !$('selector').is(':hidden');
接近 8 年之前 回复
weixin_41568131
10.24 Here's a simple benchmark testing is() against regexp:jsperf.com/jquery-is-vs-regexp-for-css-visibility. Conclusion: if you're out for performance, use regexp over is() (since is() looks for all hidden nodes first before looking at the actual element).
大约 8 年之前 回复
weixin_41568110
七度&光 I actually found that the reverse logic words better: !$('selector').is(':hidden'); for some reason. Worth a try.
8 年多之前 回复
csdnceshi75
衫裤跑路 You have a point - I'll make it clear that the code checks only for the display property. Given that the the original question is for show() and hide(), and they set display, my answer is correct. By the way it does work with IE7, here's a test snippet - jsfiddle.net/MWZss ;
9 年多之前 回复
csdnceshi68
local-host Tsvetomir, this doesn't work for IE7 - even when the elements are hidden it thinks that visible=true. Please correct your answer to avoid misleading people. visible and display are different properties and should be treated as such. Mote's answer is the correct one.
9 年多之前 回复
csdnceshi75
衫裤跑路 That is correct, but :visible will also check if the parent elements are visible, as chiborg pointed out.
9 年多之前 回复
csdnceshi72
谁还没个明天 This solution would seem to encourage the confustion of visible=false and display:none; whereas Mote's solution clearly illistrates the coders intent to check the display:none; (via mention of hide and show which control display:none not visible=true)
9 年多之前 回复

Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')
csdnceshi51
旧行李 From jQuery docs: "using :hidden heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance."
大约 2 年之前 回复
csdnceshi57
perhaps? any processing that takes more than 16ms starts dropping FPS. So yes, if it takes 42ms it can be a bad deal if you're interested in performance.
大约 3 年之前 回复
csdnceshi67
bug^君 42ms is actually a bit longer than I would like to wait for the website to respond to my actions - that means around 3 frames of animation dropped/delayed only at 60 fps
大约 4 年之前 回复
csdnceshi70
笑故挽风 The embedded presenation on the linked page no longer works, go to slideshare.net/AddyOsmani/jquery-proven-performance-tips-tricks instead.
4 年多之前 回复
csdnceshi53
Lotus@ You might want to re-read the documentation, :hidden applies to all elements. Form elements with type="hidden" is just one case that can trigger :hidden. Elements with no height and width, elements with display: none, and elements with hidden ancestors will also qualify as :hidden.
4 年多之前 回复
csdnceshi78
程序go :hidden is for form elements, not display:none. This is not the answer people are most likely expecting.
4 年多之前 回复
csdnceshi58
Didn"t forge Could you explain why this one isn't working: jsfiddle.net/URHkb ?
6 年多之前 回复
weixin_41568110
七度&光 I am toggling the element mamually using this selector. $('element:hidden') is always true for me!
接近 7 年之前 回复
csdnceshi79
python小菜 When you're dealing with a couple of elements and very little is going on - i.e. THE ABSURDLY VAST MAJORITY OF CASES - the time issue is a ridiculously minor concern. Oh, noes! It took 42 ms instead of 19 ms!!!
7 年多之前 回复
csdnceshi68
local-host On pages 21 to 28 it shows how slow :hidden or :visible is compared to other selectors. Thanks for pointing this.
大约 8 年之前 回复
csdnceshi75
衫裤跑路 just be careful, there are some good performance related tips in this presentation: addyosmani.com/jqprovenperformance
大约 9 年之前 回复

The :visible selector according to the jQuery documentation:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.

If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".

Also take into consideration the additional jQuery notes:

Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").

Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<img id="book" src="http://www.chromefusion.com/wp-content/uploads/2012/06/chrome-logo.jpg" alt="" />

Source:

Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery

jsFiddle:

JSFiddle - ipsjolly - k4WWj

</div>
csdnceshi74
7*4 until that working example goes away that is.
接近 7 年之前 回复
weixin_41568183
零零乙 but this link is showing working example of this function. I think a practical answer may weight over a full page of text :)
7 年多之前 回复

I would use CSS class .hide { display: none!important; }.

For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").

It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.

csdnceshi52
妄徒之命 Why dont you just use .is(":visible")?
接近 2 年之前 回复
csdnceshi79
python小菜 Variant you propose returns if element visible on html, my variant returns if element was directly hidden by your javascript code/view engine. If your know that parent elements should never be hidden - use .hasClass() to be more strict and prevent future bugs. If you want to check not only visibility but element state set too - use .hasClass() too. In other cases .closest() is better.
7 年多之前 回复
csdnceshi55
~Onlooker .hasClass('hide') doesn't check if an ancestor of the parent is hidden (which would make it hidden too). You could possibly get this to work correctly by checking if .closest('.hide').length > 0, but why reinvent the wheel?
接近 8 年之前 回复

Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.

So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.

So instead of an if statement, like this:

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

Or more efficient, but even uglier:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

You can do it all in one line:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
csdnceshi51
旧行李 here's is a simple example jquerypot.com/…
2 年多之前 回复
csdnceshi70
笑故挽风 No reason to extract the DOM node in the snippet used in the example, and then have to look it back up again. Better to just do: var $button = $('#btnUpdate'); And then in the If expressions just use $button instead of $(button). Has the advantage of caching the jQuery object.
8 年多之前 回复

How element visibility and jQuery works;

An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:

  • display:none hides the element, and it does not take up any space;
  • visibility:hidden hides the element, but it still takes up space in the layout;
  • opacity:0 hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;

    if ($('.target').is(':hidden')) {
      $('.target').show();
    } else {
      $('.target').hide();
    }
    if ($('.target').is(':visible')) {
      $('.target').hide();
    } else {
      $('.target').show();
    }
    
    if ($('.target-visibility').css('visibility') == 'hidden') {
      $('.target-visibility').css({
        visibility: "visible",
        display: ""
      });
    } else {
      $('.target-visibility').css({
        visibility: "hidden",
        display: ""
      });
    }
    
    if ($('.target-visibility').css('opacity') == "0") {
      $('.target-visibility').css({
        opacity: "1",
        display: ""
      });
    } else {
      $('.target-visibility').css({
        opacity: "0",
        display: ""
      });
    }
    

    Useful jQuery toggle methods:

    $('.click').click(function() {
      $('.target').toggle();
    });
    
    $('.click').click(function() {
      $('.target').slideToggle();
    });
    
    $('.click').click(function() {
      $('.target').fadeToggle();
    });
    
csdnceshi52
妄徒之命 also if you hide input with opacity:0, it still gets selected with tab key
2 年多之前 回复
csdnceshi54
hurriedly% Another difference between visibility:hidden and opacity:0 is that the element will still respond to events (like clicks) with opacity:0. I learned that trick making a custom button for file uploads.
大约 8 年之前 回复

One can simply use the hidden or visible attribute, like:

$('element:hidden')
$('element:visible')

Or you can simplify the same with is as follows.

$(element).is(":visible")
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // element is hidden
}

Above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").

For example,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.

weixin_41568183
零零乙 This answer can be used when an element exists but is not currently on the page, such as after detach().
3 年多之前 回复
csdnceshi69
YaoRaoLov This does answer the question, being the question is about a single element and by using the hide(), show() and toggle() functions, however, as most have already said, we should use the :visible and :hidden pseudo-classes.
5 年多之前 回复
csdnceshi67
bug^君 Yes, but sometimes that's what you want and I had to learn the hard way how "clever" jQuery was...
6 年多之前 回复
weixin_41568196
撒拉嘿哟木头 This is not the solution to my problem but the method helped me identify a fix for checking against a property to my problem.
6 年多之前 回复
weixin_41568184
叼花硬汉 This is the only solution that worked for me when testing with IE 8.
8 年多之前 回复
csdnceshi71
Memor.の This only checks for the display property of a single element. The :visible attribute checks also the visibility of the parent elements.
10 年多之前 回复
共29条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐