代码之家  ›  专栏  ›  技术社区  ›  Peter

如何检查隐藏DIV中的子元素是否可见?

  •  9
  • Peter  · 技术社区  · 15 年前

    我怎样才能检查隐藏的div中的div。。。是否可见?

    HTML

    <div style="display:none;">
      <div id="two_child"></div>
      <div id="three_child" style="display:none"></div>
    </div>
    

    JS公司

    if($('#two_child').is(':visible'))
    {
      alert('true');
    }
    

    有什么想法吗?

    彼得

    6 回复  |  直到 15 年前
        1
  •  18
  •   Steve Greatrex    15 年前

    你可以查一下 display

    if ($("#two_child").css("display") != "none") {
        //...
    }
    

    正如Gaby在评论中指出的,如果使用 visibility ,因此您可能希望将其扩展到:

    var $child = $("#two_child");
    if ($child.css("display") != "none" && $child.css("visibility") != "hidden") {
        //...
    }
    
        2
  •  6
  •   Community Mohan Dere    9 年前

    我已经保存了这两个选择器扩展,它们基本上与Steve的版本相同:

    another SO answer :

    // jQuery selector to find if an element is hidden by its parent
    jQuery.expr[':'].hiddenByParent = function(a) {
     return $(a).is(':hidden') && $(a).css('display') != 'none' && $(a).css('visibility') == 'visible';
    };
    

    来自Remy Sharp&Paul Irish:

    // reallyvisible - by remy sharp & paul irish
    // :visible doesn't take in to account the parent's visiblity - 'reallyvisible' does...daft name, but does the job.
    // not neccessary in 1.3.2+
    $.expr[ ":" ].reallyvisible = function(a){ return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); };
    
        3
  •  4
  •   Community Mohan Dere    9 年前

    :visible 选择器不这样工作

    :

    • 它们的CSS显示值为none。
    • type=“隐藏”。
    • 它们的宽度和高度
    • 祖先 元素是隐藏的,因此元素是

    如果要检查css属性,可以创建自定义css选择器,如中所示 Select Element By CSS style (all with given style)

        4
  •  3
  •   BrunoLM    15 年前

    display 风格, an example on jsFiddle

    $("div")
    .filter(function(){
        return $(this).css("display") == "none";
    }).find("> div").filter(function() {
        return $(this).css("display") != "none";
    }).length
    

        5
  •  -1
  •   kÍ©eÍ£mÍ®pÍ¥ Í©    15 年前

    因为隐藏元素的子元素总是隐藏在显示中,所以您可以尝试

    $("#child_two").css("style") == "none"
    

        6
  •  -4
  •   DoXicK    15 年前

    只需返回false:-)在框中找不到的项目。。。好。。。你可能把盒子里的东西弄丢了;-)