简体   繁体   中英

How do I get a useful value for height and width of a div element using javascript?

I need to be able to store the current height and width of a div at any point in time.

Currently I am using div.style.height/width which works fine when the styling is applied inline.

The problem is that this returns for example 600px and not 600.

Is there a better way to do this? If not, whats the best way to get just the number 600?

My updated code looks like this:

var div = document.getElementById('container');
div.scrollLeft = contentdim.cx*scalar - parseInt(div.style.width)/2;
div.scrollTop = contentdim.cy*scalar - parseInt(div.style.height)/2;

Which works fine in FF. For some reason scrollTop is messing up in Chrome though..

Note: This is a function which is called onscroll for the div.

try div.offsetHeight || div.clientHeight div.offsetHeight || div.clientHeight

div.style.height.replace("px","")

With jQuery, a bit more elegant, you can do it as well: http://api.jquery.com/height/

$("div").height() 
//returns just the integer

parseInt(div.style.height) is more generic than div.style.height.replace("px","")

However div.style.offsetHeight might be better because it does not rely on style being explicitly set (but you have to render the div before you can read the value)

To summarize the above:

document.getElementById('yourElement').style.height

CSS height if it has been set in a stylesheet. Will not include padding, margin, etc. If it is not set, you may wind up with values like auto .

document.getElementById('yourElement').offsetHeight

Height of the HTMLElement as rendered in the browser, including padding, scrollbars etc. (The total offset this Element's height consumes). Note that this often can be equivalent to clientHeight but that is not guaranteed.

Here is how offsetHeight is defined on Mozilla Developer Center. Note that there are a few differences with clientHeight , namely clientHeight does not include rendered scrollbars; offsetHeight will generally give you the maximum value.

Use jQuery:

height()

width()

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