For the img element in the page, to obtain its original size, take the width as an example, you may first think of width, as shown below:
Copy codeThe Code is as follows:
<Script>
Var img = document. getElementsByTagName ('img ') [0]
Var width = getWH (img, 'width') // 690
</Script>
The getWH method used here is mentioned in the previous article. The obtained width is the same as the original size of the image.
If the width attribute is added to the img, this method will not work. The actual width of the image is 690, and the width is set to 400. In this case, if the image is obtained in the preceding method, 400 is returned.
Copy codeThe Code is as follows:
<Script>
Var img = document. getElementsByTagName ('img ') [0]
Var width = getWH (img, 'width') // 400
</Script>
Obviously, 400 is not the original width of the image.
One way is to directly create a new img object and assign the src value of the old img to the new one. At this time, you can obtain the width of the new img.
Copy codeThe Code is as follows:
<Script>
Function getNaturalWidth (img ){
Var image = new Image ()
Image. src = img. src
Var naturalWidth = image. width
Return naturalWidth
}
Var img = document. getElementsByTagName ('img ') [0]
GetNaturalWidth (img) /// 690
</Script>
Note that the newly created image does not need to be added to the DOM document.
HTML5 provides a new attribute naturalWidth/naturalHeight to directly obtain the original width and height of the image. These two attributes have been implemented in Firefox/Chrome/Safari/Opera and IE9. The method for obtaining the image size under the transformation.
Copy codeThe Code is as follows:
Function getImgNaturalDimensions (img, callback ){
Var nWidth, nHeight
If (img. naturalWidth) {// modern Browser
NWidth = img. naturalWidth
NHeight = img. naturalHeight
} Else {// IE6/7/8
Var imgae = new Image ()
Image. src = img. src
Image. onload = function (){
Callback (image. width, image. height)
}
}
Return [nWidth, nHeight]
}
Note that for IE6/7/8, a new img is created, and only the src is set. In this case, the width and height of the image must be obtained after the image is fully loaded. Therefore, the callback is asynchronous. You can send a callback to pass in the original width and height as parameters.