This article mainly describes how JavaScript gets the original size of the picture in the width of the example, the need for friends can refer to the
Page of the IMG element, want to get its original size, take the width as an example may be the first thought is width, as follows
The code is as follows:
O1twaam26gomcgyaaoys716.jpg ">
<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 width you get is the same as the original size of the picture.
If the IMG plus the width attribute, this way is not, for example, the actual width of the picture is 690, set a width of 400, then the way to get the above return 400
The code is as follows:
<script> var img = document.getelementsbytagname (' img ') [0] var width = Getwh (img, ' width ')//</script>
Obviously, 400 is not the original width of the picture.
There is a way to get, directly create a new IMG object, and then the old img to the SRC assignment to the new, this time to get the new img width can be
The code is as follows:
<script> function Getnaturalwidth (img) {var image = new Image () Image.src = img.src var naturalwidth = Image.widtre Turnnaturalwidth
}
var img = document.getelementsbytagname (' img ') [0]
Getnaturalwidth (IMG)//690
</script>
It should be noted that the new image created here is not required to be added to the DOM document.
HTML5 provides a new property naturalwidth/naturalheight can directly get the original height of the picture. These two attributes have been implemented in Firefox/chrome/safari/opera and IE9. The method of obtaining picture size under transformation.
The 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 the processing of IE6/7/8, created a new IMG, only set its SRC, you need to have the picture fully loaded before you can get its width and height. So here is the asynchronous, can pass a callback, the callback to the original height as a parameter passed in.