这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
这篇文章用实例代码讲述了 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 的
方法在底层调用的是 innerWidth 属性,所以
- width()
方法获取的宽度也不是图片的原始宽度。
- 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 在各大浏览器中的兼容性如下:
图片截取自: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;
总结
以上就是这篇文章的全部内容,希望能对大家的学习或者工作带来一定的帮助。如果有疑问大家可以留言交流。
来源: http://www.phperz.com/article/17/0610/331743.html