[英]Loading image delayed display after loaded
所以我有这个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
这可能取决于脚本加载后浏览器需要渲染图像的时间。
我用你的小提琴演奏了一下,然后想到了这个:
$(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继续占据相同的空间,而不破坏页面。 而延迟是针对浏览器的,我认为对于大图像来说,渲染需要花费时间,所以让我们来给它。
这是我创建的代码的工作示例:
https://codebrace.com/editor/b16cabfee
您的baseHeight
变量未定义。 也许你应该改变
$('#base').height(baseHeight);
至
var baseHeight = $('#base').height();
更新:
我已经更新了解决方案。 在此解决方案中,我将div包裹在文本和图像上。 将环绕图像的Div设置为position:relative;
以防止图像(设置为绝对位置)覆盖文本。
你可以那样做。
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
加载后,它会调用一个回调,并使用该回调执行自定义功能。 让我知道事情的后续。
或者,顺便说一下 您可以将图像宽度和图像高度输入到自定义变量中,并在负载上进行比较,一旦达到所需的宽度和高度,则将其淡入。
您似乎在误解您的代码时间表:
#base
(文本在屏幕上不可见) #base
淡出(文本再次在屏幕上可见) 这就是为什么您在加载图像之前会短暂看到文本的原因-因为它最初并未被隐藏。
加:
display: none;
在您的#base
样式中,添加其余代码保持不变。
在添加上述CSS之后,我还创建了一个替代的JavaScript解决方案:
$(function() {
const base = $("#base"),
img = $("#img"),
backLayerSRC = img.attr('data-src'),
baseHeight = $('#base').height();
img.attr('src', backLayerSRC);
img.one("load", () => {
img.height(baseHeight).promise().done(() => { base.fadeIn(2500); });
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.