等待加载完整图像时占位符背景/图像? [英] Placeholder background/image while waiting for full image to load?

查看:66
本文介绍了等待加载完整图像时占位符背景/图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有几张图像.我发现页面在图像加载之前就开始渲染(很好),但是视觉效果不是很好.最初,用户会看到以下内容:

I have a few images on my page. I'm finding that the page starts to render before the images have been loading (which is good), but that the visual effect is not great. Initially the user sees this:

 --------hr--------
 text

然后几毫秒后,页面跳转以显示以下内容:

Then a few milliseconds later the page jumps to show this:

--------hr--------
[           ]
[   image   ]
[           ]
text

有没有一种简单的方法可以显示灰色背景图像,该图像的宽度和高度恰好是图像要占据的宽度和高度,直到图像本身加载为止?

Is there a simple way that I can show a grey background image of exactly the width and height that the image will occupy, until the image itself loads?

复杂的因素是我事先不知道图像的高度和宽度:它们是响应式的,只是将其设置为包含div的width: 100%.这是HTML/CSS:

The complicating factor is that I don't know the height and width of the images in advance: they are responsive, and just set to width: 100% of the containing div. This is the HTML/CSS:

<div class="thumbnail">
<img src="myimage.jpeg" />
<div class="caption">caption</div>
</div>
img { width: 100% } 

这里是一个JSFiddle来说明基本问题: http://jsfiddle.net/X8rTB/3/

Here's a JSFiddle to illustrate the basic problem: http://jsfiddle.net/X8rTB/3/

我已经研究过 LazyLoad 之类的东西,但我不禁感到必须有一个更简单,更简单的方法-JS答案.还是我事先不知道图像的高度是一个无法解决的问题?我确实知道图像的长宽比.

I've looked into things like LazyLoad, but I can't help feeling there must be a simpler, non-JS answer. Or is the fact that I don't know the height of the image in advance an insurmountable problem? I do know the aspect ratio of the images.

推荐答案

不是直接引用图像,而是将其粘贴在DIV中,如下所示:

Instead of referencing the image directly, stick it within a DIV, like the following:

<div class="placeholder">
    <div class="myimage" style="background-image: url({somedynamicimageurl})"><img /></div>
</div>

然后在您的CSS中:

.placeholder {
    width: 300;
    height: 300;
    background-repeat: no-repeat;
    background-size: contain;
    background-image: url('my_placeholder.png');
}

这篇关于等待加载完整图像时占位符背景/图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆