为什么对于父级隐藏的元素,getComputedStyle不返回display:none? [英] Why does getComputedStyle not return display:none for an element hidden by a parent?

查看:128
本文介绍了为什么对于父级隐藏的元素,getComputedStyle不返回display:none?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此问题页面和接受的答案此处,通过Javascript继承CSS值的正确方法是 getComputedStyle() 。但是,在以下示例中不起作用:

According to this question page and the accepted answer here, the right way to get inherited CSS values via Javascript is getComputedStyle(). However, that does not work in the following example:

<!DOCTYPE html>
<html lang="en">
<body>
    <form id="iterateThroughMe">
        <div class="notHidden"><input name="myNum" type="number" /></div>
        <div><input name="myOtherNum" type="number" /></div>
        <input name="myText" type="text" />
        <div id="hider" style="display: none;">
            <input name="hiddenElement" type="number" />
        </div>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    var inputs = $("#iterateThroughMe").find('input');
    for(var i = 0; i<inputs.length; i++) {
        var displayStyle = window.getComputedStyle(inputs[i], null).display;
        console.log(
            (($(inputs[i]).is(":hidden"))?"in":"")+
            "visible element: ",inputs[i],"has display style",displayStyle);
    }
    </script>
</body>
</html>

在浏览器中保存并打开后,控制台上将显示以下内容:

Saved and opened in a browser, the following is visible on the console:

visible element:  <input name=​"myNum" type=​"number">​ has display style inline-block
visible element:  <input name=​"myOtherNum" type=​"number">​ has display style inline-block
visible element:  <input name=​"myText" type=​"text">​ has display style inline-block
invisible element:  <input name=​"hiddenElement" type=​"number">​ has display style inline-block

在jQuery中有一种访问隐藏/可见状态的特定方法,此处,在上面的示例中可以使用,但是并非始终如此合适。为什么getComputedStyle不能区分隐藏元素和非隐藏元素,而是在所有四行上生成 inline-block 而不是 none 在输出的末尾?

There is a specific way to access hidden/visible status in jQuery, noted here, which works in the example above but is not always appropriate. Why does getComputedStyle not distinguish between hidden and non-hidden elements, producing inline-block on all four lines instead of none at the end of the output?

推荐答案

元素未呈现,因为它包含在<$ c $之内c>显示:无,,因为它已继承该值财产。

The element isn't rendered because it is contained within something that is display: none, not because it has inherited the value none for that property.

这篇关于为什么对于父级隐藏的元素,getComputedStyle不返回display:none?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆