我正在使用 jQuery (v1.7.1),并且需要获取元素的绝对浮点宽度,但 jQuery 的所有宽度方法似乎都会对宽度值进行四舍五入。
例如,如果元素的实际宽度是20.333333px
, jQuery的width方法返回20
,即忽略小数值。
你可以明白我的意思jsFiddle http://jsfiddle.net/Z2MBj/1/
所以,我的问题是:如何获取元素宽度的浮点值?
如果您已经有对 DOM 元素的引用,element.getBoundingClientRect https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect会给你你想要的价值观。
该方法自 Internet Explorer 4 起就已存在,因此在任何地方都可以安全使用。但是,那width
and height
属性仅存在于 IE9+ 中。如果您支持 IE8 及以下版本,则必须计算它们:
var rect = $("#a")[0].getBoundingClientRect();
var width;
if (rect.width) {
// `width` is available for IE9+
width = rect.width;
} else {
// Calculate width for IE8 and below
width = rect.right - rect.left;
}
getBoundingClientRect
比 快 70%window.getComputedStyle
在 Chrome 28 中,差异在 Firefox 中更大:http://jsperf.com/getcompulatedstyle-vs-getboundingclientrect http://jsperf.com/getcomputedstyle-vs-getboundingclientrect
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)