1

I'm using the following function to resize my images when I resize my browser's window:

function resize_image(a){
    $(a).on("load",function(){
        var b;
        var d=$(this).width()/$(this).height();
        var c=$(this).parent().width() / $(this).parent().height();
        if(d<c){
            b={width:"auto",height:"100%"}
        }else{
            b={width:"100%",height:"auto"}
        }
        $(this).css(b)
    })
};

That function are only working if you don't have any fixed height or width on the element. I want to have the image in a DIV tag so I can have a background-color/image that indicates that the image is loading, rather than a invisible image (as it is now).

Why I want to have a manual height that have the same height as the image, is because I have some contents under the image. When the website is loading the image, the content are at top of the website (top = 0). When the image has been loaded, the content pops down so it's under the image. I want to prevent this because the image can load a bit slow sometimes because of the web hosting and it looks kinda weird when the content are visible but not the image.

Now to my question. Is it possible to have a manual height in a DIV tag with this function, and the image resizing correctly according to the browser's window size?

4

1 回答 1

0

在加载图像之前为图像保留空间有一些技巧......

这种方法围绕着知道图像的纵横比,所以首先要考虑一些事情:

图像是否硬编码到页面中?如果是这样,您可以自己硬编码纵横比。这是最简单的方法。

如果图像是动态的并且您知道纵横比是多少,您将不得不使用其他东西来为您确定纵横比。我的建议是使用 PHP 的getimagesize() http://php.net/manual/en/function.getimagesize.php

对于这个例子,我假设你能够硬编码比率。

该技术在这里进行了相当详尽的详细介绍:

http://mobile.smashingmagazine.com/2013/09/16/responsive-images-performance-problem-case-study/

我建议阅读并忽略我的其余帖子,因为它可能会更有用。但是,这是摘要:

由于图像在加载之前不会占用任何空间,因此您不能依赖它来创建空间。但是,您可以利用填充提前预留空间。为此,需要将容器元素的高度设置为 0,以便填充完全控制元素的高度。

接下来,您要将填充设置为反映纵横比的百分比。

例如,16:9 的图像将具有 100% 的宽度,而 100% 的 9/16 为 56.25%。因此,您将对元素应用 padding-bottom: 56.25%。它现在将保留一个 16:9 的块,相对于容器的宽度,忽略子元素的高度。(也就是说,不要将该子项的高度添加到元素的总高度中,因为它已经被考虑在内。)

所以,把所有这些放在一起,你会有这样的东西:

<div class="container">
    <div class="image-space">
        <img src="something.jpg" alt="16:9 Image" />
    </div>
    <p>This space is reserved!</p>
</div>

和CSS:

.container {
    width: 50%;
    height: 300px;
}
.image-space {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
img {
    width: 100%;
}

完整示例:

http://jsfiddle.net/MeyE​​b/

*请注意,我抓取的随机图像的比例不太正确,因此您可以看到它下方的额外空间。如果你做得对,就不会发生这种情况,尽管在加大尺寸上,它有助于展示这样一个事实,即你可以在后面的那个空间放置一个背景,即使图像不存在,它也会在那里,并且可见。

于 2013-10-11T16:10:46.897 回答