Home  >  Article  >  Web Front-end  >  JavaScript gets the original size of the image, taking width as an example_javascript tips

JavaScript gets the original size of the image, taking width as an example_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:50:151081browse

If you want to get the original size of the img element in the page, taking the width as an example, the first thing you may think of is width, as follows

Copy code The code is as follows:

🎜><script> <br>var img = document.getElementsByTagName('img')[0] <br>var width = getWH(img, 'width') // 690 <br></script>

The getWH method used here is mentioned in the previous article. The width obtained at this time is the same as the original size of the image.

If you add the width attribute to img, this method will not work. For example, the actual width of the image is 690, and the width is set to 400. If you obtain it according to the above method, 400 will be returned

Copy code The code is as follows:

& lt; script & gt;
var IMG = documenn T.GetelementsBytagname ('IMG') [0]
var width = getWH(img, 'width') // 400


Obviously, 400 is not the original width of the image.

There is a way to get it, directly create a new img object, and then assign the src of the old img to the new one. At this time, you can get the width of the new img

Copy code The code is as follows: