开发者

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

开发者 https://www.devze.com 2022-12-24 07:32 出处:网络
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 w开发者_如何学运维orks fine when the styling is applied inlin

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 w开发者_如何学运维orks 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


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)


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


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()

0

精彩评论

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