所以我有这个 html/css/jQuery/js 代码,它们一起显示宽度非常大的图像。在加载并设置图像之前,基本元素应该是不可见的。然后,基本元素会通过轻微的淡入淡出变得可见。
但是行为有点不同。 加载图像后,我可以看到小文本逐渐淡入,然后需要几秒钟的时间,图像才会弹出一次(而不是像从上到下那样加载样式)
这是我使用的简化代码:
<script>
$(function() {
$("#base").hide();
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').fadeIn(500);
};
img.src = backLayerSRC;
});
</script>
<style>
#base {
position:absolute;
left:0px;
height:100%;
}
#base #img {
position:absolute;
left:0px;
top:0px;
}
</style>
<div id='base'>
some tekst
<img src='' id='img' data-src='path_to_very_large/image.png' />
</div>
现在,它怎么可能不与图像一起淡入呢?
这是一个带有图像的示例,请检查以便清楚我的意思 http://jsfiddle.net/uz8mvtap/3
最佳答案
这可能取决于脚本加载图像后浏览器需要渲染图像的时间。
我玩了一下你的 fiddle 并想出了这个:
$(function() {
$("#base").css({opacity: 0});
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').delay(1000).animate({opacity: 1.0},500);
};
img.src = backLayerSRC;
});
基本上,为此目的使用不透明度会更好,因为#base 继续占用相同的空间,不会破坏页面。延迟是针对浏览器的,我认为对于大图像来说,渲染需要时间,所以让我们给它它。
关于javascript - 加载图像加载后延迟显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52077092/