用jQuery创建等高列不工作

Creating equal height columns with jQuery not working

本文关键字:高列不 工作 创建 jQuery      更新时间:2023-09-26

我正在使用jQuery使列表项相等的高度(找到最高的,并使所有列表项等于它)。

但是代码不能识别每列中的任何内容来设置高度。它只识别8px的border-top,并将每列的高度设置为8px。我需要代码来识别列内的内容(一些h标签和p标签),找到最高的列,并使所有列都等于它。

$('#secondary').each(function(){  
        var highestBox = 0;
        $('.degreeCardInner', this).each(function(){
            if($(this).height() > highestBox) 
               highestBox = $(this).height(); 
        });  
        $('.degreeCardInner',this).height(highestBox);         
    });

请看下面的例子:JSFiddle

点击学位类别进入我正在谈论的屏幕。我试图让每个#degreeCardInner注册一个高度,考虑到所有的内容。

代码似乎可以工作,但只识别#degreeCardInner上的8px border-top,而不是其中的内容。

是否有一些我需要添加到css使此工作?

这是因为当#secondary设置为display:none;时,您正在设置页面加载时的高度(没有高度要计算)

一个可能的解决方案可能是将动态高度代码分解为自己的函数,并在#secondary第一次显示时调用它。

更新javascript:

$(document).ready(function(){
    ...
    $('#category li').on('click', function () {
            $('#main').addClass('hidden');
            $('#secondary').addClass('visible');
            if(!$('#secondary').data('heightSet'))
               setHeights();
        });
});
    function setHeights() {
        $('#secondary').each(function () {
            var highestBox = 0;
            $('.degreeCardInner', this).each(function () {
                if ($(this).height() > highestBox) highestBox = $(this).height();
            });
            $('.degreeCardInner', this).height(highestBox);
        });
        $('#secondary').data('heightSet', true);
    }

它找不到正确的元素,因为它们是隐藏的,所以这里是一个小的调整你的代码,不是在加载时运行函数而是在点击第一个函数

时运行它
$('#category').each(function () {
    var highestBox = 0;
    $('li', this).each(function () {
        if ($(this).height() > highestBox) highestBox = $(this).height();
    });
    $('li', this).height(highestBox);
}).click(function () {
    onShow();
});
function onShow() {
    $('#secondary').each(function () {
        var highestBox = 0;
        $('.degreeCardInner', this).each(function () {
            if ($(this).height() > highestBox) highestBox = $(this).height();
        });
        $('.degreeCardInner', this).height(highestBox);
    });
}