Are there any jQuery or pure JS APIs or methods to get the dimensions of an image on the page?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- How to fix IE ClearType + jQuery opacity problem i
Simply, you can test like this.
Recently I had same issue for an error in the flex slider. The first image's height was set smaller due to the loading delay. I tried the following method for resolving that issue and it's worked.
This will give you the height with respect to the width you set rather than original width or Zero.
Also (in addition to Rex and Ian's answers) there is:
and
These provide the height and width of the image file itself (rather than just the image element).
I think an update to these answers is useful because one of the best-voted replies suggests using
clientWidth
and clientHeight, which I think is now obsolete.I have done some experiments with HTML5, to see which values actually get returned.
First of all, I used a program called Dash to get an overview of the image API. It states that
height
andwidth
are the rendered height/width of the image and thatnaturalHeight
andnaturalWidth
are the intrinsic height/width of the image (and are HTML5 only).I used an image of a beautiful butterfly, from a file with height 300 and width 400. And this Javascript:
Then I used this HTML, with inline CSS for the height and width.
Results:
I then changed the HTML to the following:
i.e. using height and width attributes rather than inline styles
Results:
I then changed the HTML to the following:
i.e. using both attributes and CSS, to see which takes precedence.
Results:
With jQuery library-
Use
.width()
and.height()
.More in jQuery width and jQuery heigth.
Example Code-
JQuery Answer: