jQuery 获取元素的实际浮点宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11907514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:03:43  来源:igfitidea点击:

Getting the actual, floating-point width of an element

jquerycssfloating-pointwidth

提问by S P

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.

我正在使用 jQuery (v1.7.1) 并且我需要获取元素的绝对浮点宽度,但所有 jQuery 的宽度方法似乎都对宽度值进行了四舍五入。

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

例如,如果元素的实际宽度是20.333333px,jQuery 的宽度方法返回20,即忽略十进制值。

You can see what I mean on this jsFiddle

你可以在这个jsFiddle上看到我的意思

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

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

回答by Ross Allen

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

如果您已经拥有对 DOM 元素的引用,element.getBoundingClientRect则会获得您想要的值。

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

该方法自 Internet Explorer 4 以来就已存在,因此可以安全地在任何地方使用。但是,widthheight属性仅存在于 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;
}

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

getBoundingClientRectwindow.getComputedStyleChrome 28快 70% ,在 Firefox 中差异更大:http: //jsperf.com/getcomputedstyle-vs-getboundingclientrect

回答by John Koerner

Try this:

尝试这个:

var element = document.getElementById("a");
alert(window.getComputedStyle(element).width);

Updated fiddle: http://jsfiddle.net/johnkoer/Z2MBj/18/

更新小提琴:http: //jsfiddle.net/johnkoer/Z2MBj/18/