开发者

Convert HTML element non-px dimensions to px in (IE issue)

I'm trying to get border width of a particular element. Getting border width style setting is pretty easy by simply reading if from current calculated style of an element:

var styles = (
    document.defaultView && document.defaultView.getComputedStyle ?
  开发者_如何学Python  document.defaultView.getComputedStyle(de, null) :
    de.currentStyle
);

Reading a particular border value is then rather simple by:

var top = styles.borderTopWidth;
var value = parseFloat(top);

This is all fine and dandy (as long as you don't use IE) and I can get top border width in the value variable. But this number relates to pixels only when border width was set in pixels. If it wasn't (was em for instance) than value has the number of that particular dimension.

I have to get an answer to any of these two questions:

  1. How do I always get border width in pixels?
  2. How do I calculate different units into pixels?

Example

I've prepared a jsFiddle example where you can see various dimensions reported by DOM and jQuery. Run it in different browsers and you'll see the difference in IE. All dimansions in Crome are in integer values while Firefox calculates margin and padding in floats while border in integers.

BTW: Margin, border and padding are all set to 2mm.


Most libraries solve this problem for you, as does YUI3 for example. If you don't want to use those libraries, then at least you can peak at how they do it ;)

http://developer.yahoo.com/yui/3/api/dom-style-ie.js.html

Awnser contained therein.


You can generally get computed pixel sizes using element.offsetWidth and element.offsetHeight. This is somewhat sensitive if you want to support a range of browsers. In that case, use a library. For example, using jQuery you can get guaranteed pixel dimensions with something like this: jQuery("#theID").width().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜