我有一个包含N列的Html/JavaScript应用程序,它需要足够大,包含所有列中所有可能的LI元素。JavaScript不调整UL元素的高度有时使用Jquery插入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的是完全加载和图像已呈现“?
我认为发生的事情是,在初始页面加载时,这些LI元素的高度为0或较小的值,因为它不包含图像,所以我的resize函数正在计算错误的结果(我测试了这个带有一些警报声明)。只要LI被填充并且图像已经加载,总高度就可以很好地计算出来。
任何帮助?谢谢
在代码中究竟是在调用'resize()'函数?从我在这里可以看到的,你可以在'populateUnsetAnswers()'末尾调用它,'JavaScript'将调整大小。 – 2012-04-19 17:05:56
@KemalFadillah是的,resize()在populateUnsetAnswers()之后被调用。这只有在你刷新页面时才能在Firefox中使用。在Chrome中它依然不起作用。 – 2012-04-19 17:27:00
@FireEmblem您根本不需要设置高度,这些列将垂直扩展以适应内容。 – 2012-04-23 15:24:38