Javascript get height of div auto with currentStyle and offsetHeight

Lionsure 2020-05-20 Original by the website

When designing a web page, some elements (such as divs) cannot be fixed in advance because of how much contentId is displayed, that is, let it automatically adjust the height according to the amount of contentId, that is, adaptive height.

For the self-adaptive height of div is uncertain, how to get the current height in javascript? Generally, there are two methods, one is to get it through the currentStyle of element; the second is to get it through the offsetHeight property of element. The first method is not supported by all browsers, especially low-level browsers; the second method is compatible with all browsers.

 

I. Javascript get height of div auto with currentStyle

It can be seen from the literal meaning of currentStyle that the adaptive height of div is got through the current Css of element. Although the height of div is uncertain in advance, Css will determine its height based on its current contentId. The specific code is as follows:

<div id="contentId"></div>
       var obj = document.getElementById("contentId");
       var h = obj.currentStyle.height;

The above code, the higher version of browser can accurately get the current height of div; the lower version of browser (such as ie6) can not accurately get the current height of div, the auto is got, to accurately get the height of div need to use the following Methods.

 

II. Javascript get height of div auto with offsetHeight

The element's offsetHeight attribute, which means the displacement height; use it to accurately get the current adaptive height of div in both the high and low versions of browsers, the specific code is as follows:

<div id="contentId"></div>
       var obj = document.getElementById("contentId");
       var h = obj.offsetHeight;

If the designed webpage is required to be able to browse normally in an antique version of the old browser such as ie6, use this method; if you do not need to take into account the lower version browsers, choose the first method.