获取元素的实际浮点宽度 [英] Getting the actual, floating-point width of an element

查看:111
本文介绍了获取元素的实际浮点宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery(v1.7.1),我需要得到一个元素的绝对浮点宽度,但所有的jQuery的宽度方法似乎是四舍五入的宽度的值。

I'm using jQuery (v1.7.1) and I need to get the absolute, floating-point width of an element, but all of jQuery's width methods seem to be rounding-off the value of the width.

例如,如果元素的实际宽度 20.333333px ,jQuery的width方法会返回 20 ,即忽略小数值。

For example if the actual width of an element was 20.333333px, jQuery's width method returns 20, i.e ignoring the decimal value.

你可以看到我在这个 jsFiddle

所以,我的问题是:如何获取元素宽度的浮点值?

So, my question is: How do I get the floating-point value of the width of an element?

推荐答案

如果您已经有对DOM元素的引用,则 element.getBoundingClientRect 将为您提供所需的值。

If you already have a reference to the DOM element, element.getBoundingClientRect will get you the values you want.

该方法自Internet Explorer 4以来已存在,因此可以安全地在任何地方使用。但是, width height 属性仅存在于IE9 +中。如果您支持IE8及以下版本,则必须计算它们:

The method has existed since Internet Explorer 4, and so it's safe to use everywhere. However, the width and height attributes exist only in IE9+. You have to calculate them if you support IE8 and below:

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 %在Chrome 28中比 window.getComputedStyle 更快,Firefox中的差异更大: http://jsperf.com/getcomputedstyle-vs-getboundingclientrect

getBoundingClientRect is 70% faster than window.getComputedStyle in Chrome 28, and the differences are greater in Firefox: http://jsperf.com/getcomputedstyle-vs-getboundingclientrect

这篇关于获取元素的实际浮点宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆