当使用Jquery插入LI元素时,JavaScript有时不调整UL元素的高度

Fir*_*lem 13 html javascript ajax height

我有一个Html/JavaScript应用程序包含N列,需要足够大,包含所有列中的所有可能的LI元素.

简单的解决方案似乎计算每列中所有项目的高度,补偿填充,然后将高度设置为每列的总和.

当LI元素包含纯文本时,这很有用.不幸的是,当LI元素包含图像时,各种浏览器都存在问题.例如,当我第一次在FireFox中加载页面时,它看起来像下面的截图,但在另一次刷新时,它工作正常.它在Chrome中也无法正常工作.

屏幕截图显示UL元素的高度与LI元素不同步

我的应用程序在页面加载时不预先填充LI元素 - 它使用JavaScript,如下所示:

function populateUnsetAnswers(unsetCategoryAnswers) {
    for (i in unsetCategoryAnswers) {
        if (unsetCategoryAnswers.hasOwnProperty(i.toString())) {
            $('#categoryQuestionArea #possibleAnswers').append(
                categoryAnswerLiTag(unsetCategoryAnswers[i])
            );
        }
    }
}

function categoryAnswerLiTag(unsetCategoryAnswer) {
    var html = '<li id="' + unsetCategoryAnswer.id + '">';

    if (unsetCategoryAnswer.image) {
        html += '<img class="categoryAnswerImage" title="';
        html += unsetCategoryAnswer.text;
        html += '" src="/trainingdividend/rest/streaming/';
        html += unsetCategoryAnswer.image.fileName;
        html += '" style="height: ';
        html += unsetCategoryAnswer.image.height;
        html += ';';
        html += '" />';
    } else {
        html += unsetCategoryAnswer.text
    }

    html += '</li>';

    return html;
}
Run Code Online (Sandbox Code Playgroud)

当页面加载完成后,ajax请求将获取要放入LI元素的所有对象,然后调用上面的第一个函数.

在创建了所有LI元素之后,我在它之后调用此函数:

function resize() {
    var currentHeight, totalHeight;
    totalHeight = 0;

    $("#categoryQuestionArea ul").children().each(function() {
        currentHeight = $(this).height();

        totalHeight += currentHeight + 13;
    });

    $("#categoryQuestionArea ul").height(totalHeight);
    $("#categoryQuestionArea div#separator").css("padding-top", (totalHeight / 2) + "px");
}
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉jQuery,"不要调用resize()直到所有的LI完全加载并且图像已经呈现"?

我认为发生的事情是,在初始页面加载时,这些LI元素的高度为0或小值,因为它不包含图像,所以我的resize函数计算错误的结果(我用一些警告语句对此进行了测试).只要填充LI并且图像已加载,就可以很好地计算总高度.

有帮助吗?谢谢

Tob*_*ogh 1

如果您在第一页加载时确实遇到图像问题,可能是因为它们没有被缓存,因此无法立即可用。因此测量它们的高度会导致不好的结果...您是否调试了通过 jQuery 获取的高度(例如

currentHeight = $(this).height();
console.log(currentHeight);
Run Code Online (Sandbox Code Playgroud)

唯一的方法是我认为观察所有图像的加载事件(也可能是错误)并计算所有请求是否已完成