如何使jQuery不舍入由.width()返回的值? [英] How to make jQuery to not round value returned by .width()?
问题描述
我搜索过,找不到这个。我试图得到一个div的宽度,但如果它有一个小数点,它的数字。
I've searched around and couldn't find this. I'm trying to get the width of a div, but if it has a decimal point it rounds the number.
示例:
#container{
background: blue;
width: 543.5px;
height: 20px;
margin: 0;
padding: 0;
}
如果我做 $('#container') .width();
它将返回543而不是543.5。
If I do $('#container').width();
it will return 543 instead of 543.5. How do I get it to not round the number and return the full 543.5 (or whatever number it is).
推荐答案
使用原生 Element.getBoundingClientRect
比元素的样式。它是在IE4中引入并受所有浏览器支持:
Use the native Element.getBoundingClientRect
rather than the style of the element. It was introduced in IE4 and is supported by all browsers:
$("#container")[0].getBoundingClientRect().width
注意:对于IE8及以下版本,请参阅浏览器兼容性附注在MDN文档中。
Note: For IE8 and below, see the "Browser Compatibility" notes in the MDN docs.
$("#log").html(
$("#container")[0].getBoundingClientRect().width
);
#container {
background: blue;
width: 543.5px;
height: 20px;
margin: 0;
padding: 0;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<p id="log"></p>
这篇关于如何使jQuery不舍入由.width()返回的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!