简体   繁体   中英

How to get the height in pixels in pure javascript?

I have got a forum with the following HTML structure:

<div id="header">Contents</div>
<div id="main">Contents</div>
<div id="footer">Contents</div>

Basically, I need to set the height of #main to the height of the document minus the height of the other 2 elements. The problem is I have to do it without jquery. I googled the problem and found the clientHeight method, but it returns the height as a number, while I need it as pixels.

So, the question is:

Is there any way to get the height in pixels in pure javascript?

The property .clientHeight will return a number (the height in pixels).

In your case, below is the code to reset the height of div#main . Note that we're adding a "px" at the end for .style.height to work:

 document.getElementById('main').style.height = parseInt(window.innerHeight) - document.getElementById('header').clientHeight + document.getElementById('footer').clientHeight + "px"; 
 <div id="header">CONTENT</div> <div id="main">CONTENT</div> <div id="footer">CONTENT</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM