在窗口大小调整时动态更改div jquery的高度

时间:2013-07-23 20:33:41

标签: javascript jquery

我正在使用.each() in a div element, find a child element, set height based on its content (advanced?)中的代码 它在页面加载时工作正常但不能使用窗口调整大小请帮助

$('#col-main > div').each(function () {
    var tmpHeight = 0;
    $(this).find("h2").each(function() {
        tmpHeight = $(this).height() > tmpHeight ? $(this).height() : tmpHeight;
    });
    $(this).find("h2").height(tmpHeight);
});

在页面加载时添加工作代码 从这段代码我得到更高的div(列)" .demographcont"连续(" .box"),我设置为相同高度的行中的其他div" .demographcont"。它适用于所有行。 on normal size

不适用于窗口调整大小  它的重置高度和高度将根据内容 window resize

在页面刷新后调整窗口大小 enter image description here

/* code for adding height to div as per content */
    function setHeight() {
        $('.box').each(function () {
            var tmpHeight = 0;
            $(this).find(".demographcont").each(function () {
                tmpHeight = $(this).height() > tmpHeight ? $(this).height() : tmpHeight;
            });
            $(this).find(".demographcont").height(tmpHeight);
            // alert(tmpHeight);
        });
    }

    $(document).ready(function () {
        setHeight();
    });

    $(window).resize(function () {
        setHeight();
    });

这里的Html代码

<div class="box clearfix">
    <div class="demographcont clearfix">
        <div class="grid_12">
            <div class="grid_5">
                <label>
                    Date of Birth:</label>
            </div>
            <div class="grid_7">
                18/06/2013
            </div>
        </div>
        <div class="grid_12">
            <p>
                content1</p>
        </div>
    </div>
    <div class="demographcont">
        <div class="grid_12">
            <p>
                content1</p>
            <p>
                content1</p>
            <p>
                content1</p>
            <p>
                content1</p>
        </div>
        <div class="grid_12">
            <p>
                content1</p>
            <p>
                content1</p>
            <p>
                content1</p>
            <p>
                content1</p>
        </div>
    </div>
</div>

.demographcont {     border:1px solid#006599;     填充:0;     行高:20像素; }

1 个答案:

答案 0 :(得分:1)

好的,这就是我从你的问题中得到的:

你想找到div.demographcont元素的最大高度,并为其余的元素设置这个值。在页面加载后我们会有这样的东西

<div class="box clearfix">
    <div class="demographcont" style="height:304px">...</div>
    <div class="demographcont" style="height:304px">...</div>
</div>

现在再次在窗口调整大小时你想要做同样的事情,但正如我在评论中告诉你的那样,这是不可能的,因为你已经设置了内联相同的高度。否则我没有得到你的问题。

因此,尝试添加auto height属性,然后执行其余的proccess:

 function setHeight() {
    $('.box').each(function () {
        var tmpHeight = 0;
        $(this).find(".demographcont").each(function () {
        $(this).height('auto');
            tmpHeight = $(this).height() > tmpHeight ? $(this).height() : tmpHeight;
        });
        $(this).find(".demographcont").height(tmpHeight);
        // alert(tmpHeight);
    });
}
相关问题