html+li标签+高度,有时在使用Jquery插入LI元素时,JavaScript不会调整UL元素的高度

本文介绍如何通过JavaScript管理图片加载,使用remainingAnswerImages变量跟踪待加载图像数量,并利用onload事件确保在所有图片加载完成后调用resize()。代码示例详细展示了如何添加onload处理程序,控制加载进度,以实现流畅的用户体验。
摘要由CSDN通过智能技术生成

要真正地回答您问的问题,如果您只想在所有图像加载完成时调用resize(),那么您需要为这些图像安装onload处理程序,并且当您记录最后一个图像的加载时,您可以调用resize()函数.你可以这样做(下面的代码说明):

var remainingAnswerImages = 0;

function categoryAnswerImageLoadHandler() {

--remainingAnswerImages;

if (remainingAnswerImages === 0) {

resize();

}

}

function populateUnsetAnswers(unsetCategoryAnswers) {

// add one extra to the image count so we won't have any chance

// at getting to zero before loading all the images

++remainingAnswerImages;

var possibleAnswers$= $('#categoryQuestionArea #possibleAnswers');

for (i in unsetCategoryAnswers) {

if (unsetCategoryAnswers.hasOwnProperty(i.toString())) {

possibleAnswers$.append(categoryAnswerLiTag(unsetCategoryAnswers[i]));

}

}

// remove the one extra

--remainingAnswerImages;

// if we hit zero on the count, then there either were no images

// or all of them loaded immediately from the cache

// if the count isn't zero here, then the

// categoryAnswerImageLoadHandler() function will detect when it does hit zero

if (remainingAnswerImages === 0) {

resize();

}

}

function categoryAnswerLiTag(unsetCategoryAnswer) {

var obj = document.createElement("li");

obj.id = unsetCategoryAnswer.id;

if (unsetCategoryAnswer.image) {

// count this image

++remainingAnswerImages;

var img = new Image();

img.onload = img.onerror = img.onabort = categoryAnswerImageLoadHandler;

img.title = unsetCategoryAnswer.text;

img.style.height = unsetCategoryAnswer.image.height;

img.src = "/trainingdividend/rest/streaming/" + unsetCategoryAnswer.image.fileName;

obj.appendChild(img);

} else {

obj.innerHTML = unsetCategoryAnswer.text;

}

return obj;

}

通过说明,此代码进行了以下更改:

>添加一个变量remainingAnswerImages来跟踪还需要加载多少图像.>为每个< img>添加一个onload处理程序标签被创建,所以我们可以跟踪加载的时间.>每次我们使用onload处理程序生成一个标签的HTML,增加remainingAnswerImages.>完成添加所有HTML后,请检查其余的AustwerImages计数以查看是否为零(只有当没有图像或者所有图像立即从浏览器缓存中加载时,才会这样).如果是这样,请立即调用resize().>在将为每个图像调用的onload处理程序中,减少remainingAnswerImages,如果计数达到零,调用resize().>在添加图像时,添加一个额外的剩余的作为一个门,以防止得到零计数,直到我们完成添加图像.完成添加图片后,再加一点.>我还重写了类别AnswerLiTag()函数,直接创建DOM对象,而不是将一串字符串并入HTML.在这种情况下,代码是更清洁的阅读和维护.>我还将$(‘#categoryQuestionArea #possibleAnswers’)从你的for循环中移出,因为它每次都解析为同样的事情.更好地在循环之前做一次.此外,在大多数情况下,这可以简化为$(‘#possibleAnswers’),因为ids应该在页面中是唯一的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值