Simple Example of JS getting IMG image height and width, js getting img width

Source: Internet
Author: User

Simple Example of JS getting IMG image height and width, js getting img width

Some time ago, when I added the adaptive screen size function to the touchslider. js carousel code written by LJW, I encountered a problem. No matter what method you use, you cannot obtain the height and width of the IMG tag. In the end, you only need to set a ratio of height and width for the image. When you are free today, I wrote a few demos to test it, I found the reason, and listened to me in detail. If anything is wrong, please make a brick ~~~

First, the method for obtaining the height and width is as follows:


Obj. style. width (height );

Obj. offsetWidth (offsetHeight );

Obj. clientWidth (clientHeight );

GetComputedStyle and currentStyle;

Obj. naturalWidth (naturalHeight)

For the sake of simplicity, width is used as an example.

First, let's talk about the first method: obj. style. width. This method can be obtained only when the width size is written into the style attribute in the label. Otherwise, only null is returned. Take a look at the demo below:


<img style = "width: 400px" src = "http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">
<script>
var imgW = document.getElementsByTagName ('img') [0] .style.width;
   alert (imgW); // The return value is 400px, otherwise it returns empty;
</ script>

The above method only applies to adding the width value to the style attribute of the label and adding the width value to the introduced style table (whether it is link or html page using the style label) similarly, the returned value is null if no value is obtained.

Then let's talk about the second method and the third method obj. offsetWidth (offsetHeight); obj. clientWidth (clientHeight); generally, if the padding value and border value are not set for the tag, the two obtain the same value. However, this is not the case in many cases. In fact, offsetWidth obtains the width value + padding value + border value. clientWidth obtains the width value + padding value. See the demo below:

<style>
img{ padding:20px;border:1px solid red;}
</style>
<img style="width:400px" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">
<script>
var img = document.getElementsByTagName('img')[0], 
      imgOffsetWidth = img.offsetWidth, //442px
      imgClientWidth = img.clientWidth; //440px;
</script>

Note that the width of the obtained img label is the style = "width: 400px" added to the img label ". If this attribute value is removed, the values returned by imgOffsetWidth and imgClientWidth in the demo above are the height and width of the image. You can try it out.

In addition, getComputedStyle and currentStyle are two methods for processing compatibility. The obtained values are only the image width values displayed on the screen, the padding and border values of the img label are not obtained. However, getComputedStyle applies to Firefox/IE9/Safari/Chrome/operabrowser, and currentStyle applies to IE6/7/8. However, if the img label does not introduce a style table even if the style attribute is not set, only getComputedStyle can get the value, that is, the image height and width, and currentStyle returns auto. There is a demo below:

<img style="width: 400px;" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">

  <script>
    function getStyle(el, name) {
      if(window.getComputedStyle) {
        return window.getComputedStyle(el, null)[name];
      }else{
        return el.currentStyle[name];
      }
    }
    var div = document.getElementsByTagName('img')[0];
    alert(getStyle(div, 'width'));
  </script>

You can remove the style attribute from the img label and then test it.

Finally, the obj. naturalWidth (naturalHeight) method is used. This is a newly added method for retrieving the height and width of elements in HTML5, but it is only applicable to Firefox/IE9/Safari/Chrome/operabrowser. Below is a demo for each Browser:

<img style = "width: 400px;" src = "http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">

   <script>
     document.addEventListener ('DOMContentLoaded', function () {
       function getImgNaturalStyle (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]
       }
       var img = document.getElementsByTagName ('img') [0],
           imgNatural = getImgNaturalStyle (img);
       alert (imgNatural);
     });
   </ script>

Note that in IE6/7/8, image. src is obtained only after the img image is fully loaded. Otherwise, an error is returned.

When it comes to the full loading of images, it solves the problem that the Image Height cannot be obtained from the last time I encountered it with LJW;

document.addEventListener ("DOMContentLoaded", function () {

     // The reason is that our code was written in such an environment. At this time, only the img tag is loaded, that is, only the DOM structure, and the image has not been fully loaded. Therefore, the obtained values are all 0, but if Write in the window.onloaded environment, you can get the height and width shown

}); 

That is to say, the above methods for obtaining the image height and width must be based on the fact that the image has been fully loaded.

Well, I can only understand it here with my ability. If anything is wrong, please make a brick ~~

The above JS simple example of getting IMG images with high width is all the content shared by xiaobian. I hope to give you a reference, and I hope you can provide more support for the customer's house.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.