在CSS中,元素的高度和宽度设置为auto。我想在页面首次加载后获取此元素的高度。我检查$('#minor'),它确实具有clientHeight:333,clientWidth:826,但是无法获取clientHeight,clientWidth,offsetHeight和offsetWidth的值。但是,我可以正确获得$('#minor')的其他属性。

顺便说一句,我可以得到#gallery和#image_holder的clientWidth,尽管它们的宽度也设置为auto。

对于clientHeight,所有元素的clientheight无法正确获取,它始终返回20

骨干网查看代码:

var SubheaderView = Backbone.View.extend({
    id: 'gallery',
    tagName: 'div',

    initialize: function() {
        $(window).on('resize', this.updateCss); #=> it works correctly
        this.render();
    },

    render: function() {
        this.$el.append(subheaderTemplate);
        var that = this;
        _.defer(function(){
            that.updateCss();
        });

        return this;
    },

    updateCss: function() {
        console.log($('#minor')[0].clientHeight); #=> it still return 20
        console.log($('#minor')[0].clientWidth); #=> it still return 0
        console.log($('#minor')[0].localName); #=> it return div
    }
});


subheaderTemplate html代码:

<div id="image_wrapper">
    <div id="image_holder">
        <div class="image_item" id="major">
            <img src="media/images/test/image1.png" alt="major image">
        </div>

        <div class="image_item" id="minor">
            <img src="media/images/test/image2.png" alt="minor image">

            <div id="cover">
                <h1>Over 196 Homes<br>Sold a Week<br>Through Real Estate</h1>
            </div>
        </div>

        <div class="image_item">
            <img src="media/images/test/image3.png"alt="image">
        </div>
        <div class="clearfix"></div>
    </div>
</div>


CSS文件:

#gallery {
    margin-top: 1px;
    width: auto;
    height: auto;
    background-color: #fefefe;
}

#image_wrapper {
    width: 87%;
    height: auto;
    margin: 0px auto 0px auto;
    overflow: visible;
}

#image_holder {
    width: auto;
    height: auto;
}

#image_wrapper .image_item {
    position: relative;
    width: auto;
    height: auto;
    float: left;
    background-color: blue;
    border: none;
}

#minor {
    overflow: hidden;
}

#image_wrapper img {
    width: 100%;
    border: none;
}

#cover {
    position: absolute;
    top: 0px;
    width: 100%;
    height: 337px;
    background-color: #101010;
    background-color: rgba(16,16,16,0.7);
}

#cover h1 {
    color: #b7aeab;
    line-height: 97%;
    font-size: 33px;
    padding: 133px 0px 0px 39px;
}

最佳答案

高度和宽度的计算是基于其他元素的,因此,我相信浏览器只有在加载了更多页面之后才能告诉您。甚至defer的延迟可能也不够,因为只有1ms。

您是否尝试过将像这样的高度检查代码放在$块中?

$(function() {
    alert($('#minor').height());
});


如果没有,我会尝试,甚至可能:

$('body').on('load', function() {
    alert($('#minor').height());
});

09-25 17:02
查看更多