Столбцы одинаковой высоты, которые пересчитываются при изменении размера окна

Код, который я ниже, должен найти высоту самого большого столбца (.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>

person Rich    schedule 04.03.2013    source источник
comment
Есть ли причина, по которой CSS columns не подходит?   -  person Niet the Dark Absol    schedule 05.03.2013
comment
@Колинк Есть. Подводя итог, это просто не вариант.   -  person Rich    schedule 05.03.2013


Ответы (3)


Используйте плагин 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/.

person zamnuts    schedule 04.03.2013

Это не совсем решение вашей проблемы с JavaScript. Это решение CSS, которому не нужен JavaScript. Используя эти стили с вашей разметкой, оба столбца всегда будут иметь одинаковую высоту:

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

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

Демо

http://jsfiddle.net/wmbcr/

Это будет работать и при изменении размера, если не установлена ​​фиксированная ширина.

person insertusernamehere    schedule 04.03.2013
comment
Мне нужно, чтобы тег ‹a› отображал: встроенный блок. В противном случае это было бы хорошо. - person Rich; 05.03.2013
comment
Можете ли вы сказать, почему? Может быть, мы сможем найти решение, которое не разрушит весь ваш макет. - person insertusernamehere; 05.03.2013

Я думаю, вы должны указать высоту своего DIV, а не <a>.

Попробуйте эту скрипку:

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

person Peeyush    schedule 04.03.2013
comment
@rick, вы тоже можете сделать это, но сначала вам нужно установить его display:block; см. этот stackoverflow.com/questions/4743254/ - person Peeyush; 05.03.2013
comment
мой якорь настроен на display:inline-block; - person Rich; 05.03.2013