将 HTML 元素非 px 尺寸转换为 px (IE 问题)
我正在尝试获取特定元素的边框宽度。 通过简单地从元素的当前计算样式中读取 if 来获取边框宽度样式设置非常容易:
var styles = (
document.defaultView && document.defaultView.getComputedStyle ?
document.defaultView.getComputedStyle(de, null) :
de.currentStyle
);
读取特定边框值则相当简单:
var top = styles.borderTopWidth;
var value = parseFloat(top);
这一切都很好(只要您不使用 IE) ),我可以在 value
变量中获取顶部边框宽度。但这个数字仅当边框宽度以像素为单位设置时才与像素相关。如果不是(例如,是 em
),则 value
具有该特定维度的编号。
我必须回答这两个问题中的任何一个:
- 如何始终获得边框宽度(以像素为单位)?
- 如何将不同单位计算为像素?
示例
我准备了一个 jsFiddle 示例,您可以在其中看到 DOM 和 jQuery 报告的各种维度。在不同的浏览器中运行它,你会看到 IE 中的差异。 Crome 中的所有尺寸均采用整数值,而 Firefox 则以浮点数计算边距和填充,而边框以整数计算。
顺便说一句:边距、边框和内边距均设置为2mm。
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 ?
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:
- How do I always get border width in pixels?
- 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
大多数库都会为您解决这个问题,例如 YUI3。
如果您不想使用这些库,那么至少您可以了解它们是如何做到的;)
http://developer.yahoo.com/yui/3/api/dom-style-ie.js.html
其中包含 Awnser。
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.
通常,您可以使用 element.offsetWidth 和 element.offsetHeight 获取计算出的像素大小。如果您想支持一系列浏览器,这有点敏感。在这种情况下,请使用库。例如,使用 jQuery,您可以获得有保证的像素尺寸,如下所示:jQuery("#theID").width()。
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().