我有一個包含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