img.on(“load”)在加载img之后但在它的大小设置(IE)之前执行

编辑 :添加了jsfiddle

  • (for) https://jsfiddle.net/x60bwgw7/4/

  • (每个) https://jsfiddle.net/v3y2v8cf/3/

  • 在IE中打开 ,输出值为30是错误的(IE占位符高度)

  • 我试图返回DOM naturalHeight和clientHeight,虽然naturalHeight在IE中正常工作,但clientHeight(我需要的那个)却没有。

  • 这是一个明显的解决方法,但它有点糟糕https://jsfiddle.net/0rhjt0wn/1/

  • 似乎问题是IE 加载渲染图像,而其他浏览器在加载时渲染它,但我只是在这里猜测。

我有一些图像,我想通过将它们的“data-src”属性值分配给它们的“src”属性并在其后垂直居中来加载。

除了IE(从8到边缘测试)之外,它在所有浏览器中都没有问题。

在IE中,一些图像在没有问题的情况下居中,但是有些图像不会因为.on(“load”)事件中的代码在加载图像之后(可能)在执行其大小设置之前执行。

有没有办法在加载图像并设置其大小(在IE中)后始终执行代码?

for (i = 0; i < 100; i++) { targetSrc = $divElement.eq(i).children(imgClass).attr(dataSrc) + "?v=" + datetime; $divElement.eq(i).find(imgClass).attr("src", targetSrc).on("load", function() { $holder.append($(this).attr("src") + " || height = " + $(this).height() + "
"); }); }

最初认为requestAnimationFrame和超时回退可以很容易地解决这个问题,但事实certificate它要复杂得多。 显然,在onload之后呈现图像的确切帧在IE中是不可预测的。 但是我最终提出了这个解决方案, naturalHeight高度与当前高度进行比较,以查看是否已经渲染了图像,当情况不是这样时,循环到下一个显示帧:

https://jsfiddle.net/r8m81ajk/

 $(function() { if (window.requestAnimationFrame) var modern = true; var element = $('.divElement'), reference = '.imgElement', holder = $('.holder'), datetime = Date.now(), path, image; for (var i = 0; i < 100; i++) { var target = element.eq(i).children(reference), path = target.data('src') + '?v=' + datetime; target.one('load', function() { image = this; if (modern) requestAnimationFrame(function() { nextFrame(image); }); else setTimeout(renderImage, 50); }).attr('src', path); } function nextFrame(picture) { var dimension = $(picture).height(); if (dimension == picture.naturalHeight) { holder.append('height = ' + dimension + '
'); } else nextFrame(picture); } function renderImage() { holder.append('height = ' + $(image).height() + '
'); } });

后备将始终检查第三帧(当没有瓶颈时)。 不介意我将代码调整到我惯常的惯例,外部引用应该保持不变。

从问题我意识到甚至可能不需要循环,并且当图像加载足够时获得naturalHeight 。 有趣的运动,以检测任何情况下的渲染的确切点。