【发布时间】:2012-04-28 09:38:18
【问题描述】:
我有一个 Html/JavaScript 应用程序,其中包含 N 列,这些列需要足够大,包含所有列中所有可能的 LI 元素。
简单的解决方案似乎是计算每列中所有项目的高度,补偿填充,然后将高度设置为每列的总高度。
当 LI 元素包含纯文本时,这很有效。不幸的是,当 LI 元素包含图像时,各种浏览器都会出现问题。例如,当我第一次在 FireFox 中加载页面时,它看起来像下面的屏幕截图,但在再次刷新时,它工作正常。它在 Chrome 中也无法正常工作。
我的应用程序在页面加载时没有预先填充 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;
}
页面加载完成后,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");
}
有什么方法可以告诉 jQuery,“在所有的 LI 完全加载并且图像已经渲染之前,不要调用 resize()”?
我认为发生的情况是在初始页面加载时,这些 LI 元素的高度为 0 或一个较小的值,因为它不包含图像,所以我的 resize 函数正在计算错误的结果(我用一些警告声明)。只要填充了 LI 并且加载了图像,就可以很好地计算总高度。
有什么帮助吗?谢谢
【问题讨论】:
-
您在代码中的哪个位置调用了
resize()函数?从我在这里看到的情况来看,你可以在populateUnsetAnswers()的末尾调用它,JavaScript会正确调整大小。 -
@KemalFadillah 是的,resize() 已经在 populateUnsetAnswers() 之后调用了。这仅在您进行页面刷新时在 Firefox 中有效。它在 Chrome 中仍然无法正常工作。
-
@FireEmblem 你根本不需要设置高度,列会垂直扩展以适应内容。
-
你在我们可以现场看到的地方做一个演示吗?像 jsfiddle
-
请您编辑您的问题,添加完整代码(HTML、CSS、JavaScript)或演示(可能在 [jsfiddle.net/](jsFiddle))。如果没有完整的问题,很难找到解决方案。看到已经给出的大多数答案实际上都是猜测!
标签: javascript html ajax height