设置图像的宽度/高度以避免在图像加载时回流 [英] Set width/height of image to avoid reflow on image load

查看:286
本文介绍了设置图像的宽度/高度以避免在图像加载时回流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在html中使用图片标签时,我试着在 img 标签中指定它的宽度和高度,这样浏览器会为它们保留空间,甚至在图像被加载,所以当它们完成加载时,页面不会重排(元素不会四处移动)。例如:

 < img width =600height =400src =.../> 

现在的问题是我想要创建一个更响应的版本,其中单列我想这样做:

 < img style =max-width:100%src = .../> 

但是,如果我将它与明确指定的宽度和高度混合,如:

 < img style =max-width:100%width =600height =400src =.../> ; 

并且图像宽于可用空间,则忽略宽高比调整图像大小。我明白为什么会发生这种情况(因为我固定图像的高度),我想解决这个问题,但我不知道如何解决。总结:我希望能够指定 max-width:100%,并且在加载图像时确保内容不会被重排。

解决方案

我也在寻找这个问题的答案。使用 max-width width = height = ,浏览器拥有足够的数据,它应该能够为图像留下适当的空间,但它似乎不能以这种方式工作。



我现在用一个jQuery解决方案解决了这个问题。它要求您为< img> 提供 width = / code>标签。



CSS:

  img {max-width:100%;身高:自动; } 

HTML:

 < img src =image.pngwidth =400height =300/> 

jQuery:

($)$(this).attr('height')/ $(this).attr ('width')* 100;
$(this).wrap('< div style =padding-bottom:'+ aspect_ratio +'%>');
});

这会自动应用以下技术: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/


When I use image tags in html, I try to specify its width and height in the img tag, so that the browser will reserve the space for them even before the images are loaded, so when they finish loading, the page does not reflow (the elements do not move around). For example:

<img width="600" height="400" src="..."/>

The problem is now I want to create a more "responsive" version, where for the "single column case" I'd like to do this:

<img style="max-width: 100%" src="..."/>

but, if I mix this with explicitly specified width and height, like:

<img style="max-width: 100%" width="600" height="400" src="..."/>

and the image is wider than the available space, then the image is resized ignoring the aspect ratio. I understand why this happens (because I "fixed" the height of the image), and I would like to fix this, but I have no idea how.

To summarize: I want to be able to specify max-width: 100%, and also somehow make sure the content is not reflowed when the images are loaded.

解决方案

I'm also looking for the answer to this problem. With max-width, width= and height=, the browser has enough data that it should be able to leave the right amount of space for an image but it just doesn't seem to work that way.

I worked around this with a jQuery solution for now. It requires you to provide the width= and height= for your <img> tags.

CSS:

img { max-width: 100%; height: auto; }

HTML:

<img src="image.png" width="400" height="300" />

jQuery:

$('img').each(function() { 
    var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100;
    $(this).wrap('<div style="padding-bottom: ' + aspect_ratio + '%">');
});

This automatically applies the technique seen on: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

这篇关于设置图像的宽度/高度以避免在图像加载时回流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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