在窗口调整大小时重新计算的等高列

时间:2013-03-04 23:11:20

标签: javascript jquery window-resize

我下面的代码应该找到最大列(.border)的高度,并调整.container div中找到的任何其他列的高度等于它。不幸的是,我无法让这些代码按预期工作,所以我希望有人能比我更聪明可以帮助我。

还值得一提的是,每当调整窗口大小时,应重新计算列高度并分别调整列大小。

<script type="text/javascript">
    $(document).ready(function(){
        //Bind the window onresize event
        $(window).bind('resize', resizeWindow);

        //Call resizeWindow() function immediately to intiially set elements
        resizeWindow();
    });

    function resizeWindow(){
        //Find all the container parent objects
        $('.container').each(function(){
            //Initialize the height variable
            var maxHeight = 0;

            //Cache the jQuery object for faster DOM access and performance
            var $borders = $(this).find('.border');

            //Find all the border child elements within this specific container
            $borders.each(function(){
                //Get current element's height
                var thisHeight = $(this).height();

                //Check if the current height is greater than the max height thus far
                //If so, change max height to this height
                if (thisHeight>maxHeight) maxHeight = thisHeight;
            });

            //Now that we have the maximum height of the elements,
            //set that height for all the .border child elements inside the parent element
            $borders.height(maxHeight);
        });
    }
</script>


<div class="container">
    <a href="#" class="border">
        <div class="column">
            <div class="content">asdf</div>
        </div>
    </a>
    <a href="#" class="border">
        <div class="column">
            <div class="content">asdf</div>
        </div>
    </a>
</div>

3 个答案:

答案 0 :(得分:1)

使用jQuery equalHeights插件:

http://www.cssnewbie.com/equalheights-jquery-plugin

$('.container .border').equalHeights(); // make all .border the same height
$(window).resize(function(){$('.container .border').equalHeights();});

请参阅:http://jsfiddle.net/rZU35/

答案 1 :(得分:0)

这不完全是您的JavaScript问题的解决方案。这是一个CSS解决方案,不需要任何JavaScript。将这些样式与标记一起使用时,两列的长度始终相同:

div.container {
    display: table;
    width: 100px;
}

div.container > a {
    display: table-cell;
    border: 1px solid red;
}

<强>演示

http://jsfiddle.net/wmbcr/

如果没有设置固定宽度,这也适用于调整大小。

答案 2 :(得分:0)

我认为您应该为DIV而不是<a>提供高度。

试试这个小提琴:

http://jsfiddle.net/ddFtX/1/

相关问题