开发者

How to get height of <div> in px dimension

I have used jQuery library to find out height of a div.

Below is my div element with attributes :

<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test<开发者_JAVA百科/DIV>

Below is my jQuery code to get height of <div>

var result = $("#myDiv").css('height');
alert(result);

After executing above statement I am getting result as "auto". Actually this is I am not expecting, instead of that I want the result in px dimension.


Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:

javascript:

var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;

or in jquery:

$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();


Use .height() like this:

var result = $("#myDiv").height();

There's also .innerHeight() and .outerHeight() depending on exactly what you want.

You can test it here, play with the padding/margins/content to see how it changes around.


Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;


There is a built-in method to get the bounding rectangle: Element.getBoundingClientRect.

The result is the smallest rectangle which contains the entire element, with the read-only left, top, right, bottom, x, y, width, and height properties.

See the example below:

let innerBox = document.getElementById("myDiv").getBoundingClientRect().height;
document.getElementById("data_box").innerHTML = "height: " + innerBox;
body {
  margin: 0;
}

.relative {
  width: 220px;
  height: 180px;
  position: relative;
  background-color: purple;
}

.absolute {
  position: absolute;
  top: 30px;
  left: 20px;
  background-color: orange;
  padding: 30px;
  overflow: hidden;
}

#myDiv {
  margin: 20px;
  padding: 10px;
  color: red;
  font-weight: bold;
  background-color: yellow;
}

#data_box {
  font: 30px arial, sans-serif;
}
Get height of <mark>myDiv</mark> in px dimension:
<div id="data_box"></div>
<div class="relative">
  <div class="absolute">
    <div id="myDiv">myDiv</div>
  </div>
</div>


For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜