Home  >  Article  >  Web Front-end  >  Detailed explanation of how JavaScript obtains the true size of an image

Detailed explanation of how JavaScript obtains the true size of an image

黄舟
黄舟Original
2017-03-16 15:20:421600browse

网页页面上的图片尺寸似乎都千篇一律。我们最常见到的带有多图的文章页面中,图的大小通常是和页面的宽度一致,这样看起来,页面就是一个直筒形,这样的布局看多了就会觉得很单调。之所以形成这样的局面,我想很大程度上是因为老式浏览器的限制。但随着现代浏览器(火狐/谷歌/IE11)的普及,浏览器对页面设计的限制越来越少,Web程序员的想象能力能够得到极大的发挥。

比如,冷知识:你知道每个视窗都有的 [x] 是怎么来的吗?这篇文章中,很多图片超出了文本宽度的限制,给人一种参差错落的感觉,同时,让大图片以其真实的尺寸展示,给人以更震撼的感觉。

但从技术上,我们可以轻松的用文本的最大宽度限制图片,让它们都保持一个宽度,而不按文本的宽度时,我们就需要每个图片的自己的尺寸。我们可以在服务端编辑时声明图片的原始尺寸。而一种更灵活的方式是通过在页面上放一段js来动态的获取图片的原始大小尺寸,动态改变图片的显示大小。这样即能兼容老的也文本最大宽度的方式,还可以在需要的时候让图片呈现出其原始的大小。

如何用JavaScript在浏览器端获取图片的原始尺寸大小?

var img = $(“#img_id”); // Get my img elem
var pic_real_width, pic_real_height;
$(“<img/>”) // Make in memory copy of image to avoid css issues
.attr(“src”, $(img).attr(“src”))
.load(function() {
pic_real_width = this.width;   // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});

Webkit浏览器(谷歌浏览器等)是在图片的loaded事件之后才能获取高度和宽度值。所以,你不能使用timeout函数延时等待,最好的方法是使用图片的onload事件。

为了避免CSS对图片大小尺寸的影响,上面的代码将图片拷贝到内存中进行计算。

如果你的页面是老式页面,你可以按需把这段代码嵌入页面底部,它不需要你修改原有页面

The above is the detailed content of Detailed explanation of how JavaScript obtains the true size of an image. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn