gpt4 book ai didi

javascript - 加载图片延迟加载后显示

转载 作者:行者123 更新时间:2023-11-28 14:47:47 25 4
gpt4 key购买 nike

所以我有这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com