简体   繁体   English

当内容更改高度时动态更改容器div的高度

[英]Dynamically change height of container div when content changes height

I have a website with different sections, each set to be the height of the browser window. 我有一个包含不同部分的网站,每个部分设置为浏览器窗口的高度。 In some cases, the content is taller than the browser window, and I use a function to check for this and set the height of the div to be the height of its content, using the function: 在某些情况下,内容比浏览器窗口高,我使用一个函数来检查这一点,并使用以下函数将div的高度设置为其内容的高度:

$('.container').each(function() {
        var _this = $(this);
        var this_ = this;
        var windowH = $(window).height();
        var textH = $('.text', this).height();
        if(windowH < textH) {                            
            $(this).css({'height': textH + 'px'});
        }
        else {
            $(this).css({'height': windowH + 'px'});
        }
        $(window).resize(function(){
            var windowH = $(window).height();
            var textH = $('.text', this_).height();
            if(windowH < textH) {
                _this.css({'height': textH + 'px'});
            }
            else {
                _this.css('height', windowH + 'px');
            }

        });         
    });

The issue I am having is that I want to dynamically hide and show content, and when the new content is taller than the current height of the div, I want the div to expand to contain it. 我遇到的问题是我想动态隐藏和显示内容,并且当新内容高于div的当前高度时,我希望div扩展以包含它。 I am using the function, 我正在使用该功能,

$('#container').on('click', 'p', function () {
    $(this).height('300px');
    var windowH = $(window).height();
    $('#container').css({
        'height': ($('#container .text').height() + 'px')
    });
    var textH = $('#container').height();
    if (windowH < textH) {
        $('#container').css({
            'height': textH + 'px'
        });
    } else {
        $('#container').css('height', windowH + 'px');
    }

});

but with no success. 但没有成功。 I have created a fiddle, http://jsfiddle.net/wDRzY/ 我创建了一个小提琴, http://jsfiddle.net/wDRzY/

Using a nested div, limit the height of the outer div and let the inner div stay the height of the content. 使用嵌套的div,限制外部div的高度,并让内部div保持内容的高度。 When you need the outer div to be the height of the content, you can set the outer div height equal to the inner div height. 当需要将外部div设置为内容的高度时,可以将外部div的高度设置为等于内部div的高度。

Although, I'm not sure why you would need to do this at all. 虽然,我不确定您为什么需要这样做。 I would suggest reading up on CSS more and using that for display purposes like this. 我建议更多地阅读CSS并将其用于这样的显示目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM