国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Javascript獲取圖片原始寬度和高度的方法詳解

2019-11-20 08:56:44
字體:
來源:轉載
供稿:網友

前言

網上關于利用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里已經實現(xiàn)。

如下:

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

naturalWidth / naturalHeight在各大瀏覽器中的兼容性如下:

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

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

IE7/8中的兼容性實現(xiàn):

在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+瀏覽器都能兼容的函數(shù)封裝:

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;

總結

以上就是這篇文章的全部內容,希望能對大家的學習或者工作帶來一定的幫助。如果有疑問大家可以留言交流。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 巨野县| 阿拉善右旗| 县级市| 赣州市| 炉霍县| 嘉禾县| 嘉荫县| 会昌县| 鄂托克前旗| 凌源市| 万安县| 友谊县| 彭州市| 绵阳市| 长葛市| 明溪县| 临漳县| 改则县| 洛阳市| 依安县| 垣曲县| 信宜市| 石柱| 阿坝县| 东海县| 临城县| 芮城县| 衡水市| 北宁市| 盱眙县| 青河县| 白沙| 曲靖市| 南城县| 高清| 滦南县| 苍南县| 萨嘎县| 沅陵县| 涪陵区| 百色市|