手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Javascript获取图片原始宽度和高度的方法详解
Javascript获取图片原始宽度和高度的方法详解
摘要:前言网上关于利用Javascript获取图片原始宽度和高度的方法有很多,本文将再次给大家谈谈这个问题,或许会对一些人能有所帮助。方法详解页面...

前言

网上关于利用Javascript获取图片原始宽度和高度的方法有很多,本文将再次给大家谈谈这个问题,或许会对一些人能有所帮助。

方法详解

页面中的img元素,想要获取它的原始尺寸,以宽度为例,可能首先想到的是元素的innerWidth属性,或者jQuery中的width()方法。

如下:

<img id="img" src="1.jpg"> <script type="text/javascript"> var img = document.getElementById("img"); console.log(img.innerWidth); // 600 </script>

这样貌似可以拿到图片的尺寸。

但是如果给img元素增加了width属性,比如图片实际宽度是600,设置了width为400。这时候innerWidth为400,而不是600。显然,用innerWidth获取图片原始尺寸是不靠谱的。

这是因为 innerWidth属性获取的是元素盒模型的实际渲染的宽度,而不是图片的原始宽度。

<img id="img" src="1.jpg" width="400"> <script type="text/javascript"> var img = document.getElementById("img"); console.log(img.innerWidth); // 400 </script>

jQuery的width()方法在底层调用的是innerWidth属性,所以width()方法获取的宽度也不是图片的原始宽度。

那么该怎么获取img元素的原始宽度呢?

naturalWidth / naturalHeight

HTML5提供了一个新属性naturalWidth/naturalHeight可以直接获取图片的原始宽高。这两个属性在Firefox/Chrome/Safari/Opera及IE9里已经实现。

如下:

var naturalWidth = document.getElementById('img').naturalWidth, naturalHeight = document.getElementById('img').naturalHeight;

naturalWidth / naturalHeight在各大浏览器中的兼容性如下:

Javascript获取图片原始宽度和高度的方法详解1

图片截取自:http://caniuse.com/#search=naturalWidth

所以,如果不考虑兼容至IE8的,可以放心使用naturalWidth / naturalHeight属性了。

IE7/8中的兼容性实现:

在IE8及以前版本的浏览器并不支持naturalWidth和naturalHeight属性。

在IE7/8中,我们可以采用new Image()的方式来获取图片的原始尺寸,如下:

function getNaturalSize (Domlement) { var img = new Image(); img.src = DomElement.src; return { width: img.width, height: img.height }; } // 使用 var natural = getNaturalSize (document.getElementById('img')), natureWidth = natural.width, natureHeight = natural.height;

IE7+浏览器都能兼容的函数封装:

function getNaturalSize (Domlement) { var natureSize = {}; if(window.naturalWidth && window.naturalHeight) { natureSize.width = Domlement.naturalWidth; natureSizeheight = Domlement.naturalHeight; } else { var img = new Image(); img.src = DomElement.src; natureSize.width = img.width; natureSizeheight = img.height; } return natureSize; } // 使用 var natural = getNaturalSize (document.getElementById('img')), natureWidth = natural.width, natureHeight = natural.height;

总结

以上就是这篇文章的全部内容,希望能对大家的学习或者工作带来一定的帮助。如果有疑问大家可以留言交流。

【Javascript获取图片原始宽度和高度的方法详解】相关文章:

JavaScript检查子字符串是否在字符串中的方法

JavaScript实现文本框中默认显示背景图片在获得焦点后消失的方法

JavaScript中reduce()方法的使用详解

JavaScript中的splice()方法使用详解

javascript动态创建链接的方法

JavaScript中的Math.LN2属性用法详解

JavaScript中toString()方法的使用详解

JavaScript中switch语句的用法详解

JavaScript中的anchor()方法使用详解

javascript判断并获取注册表中可信任站点的方法

精品推荐
分类导航