<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../../js/jquery/jquery1.2.6.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="ddd" style="height:50.5px;"></div>
</body>
<script type="text/javascript">
alert(jQuery("#ddd").height());
</script>
</html>
会弹出51。查看源码会发现,height
方法实际调用的是dom对象的offsetHeight属性,而这个属性会自动四舍五入。
解决方法
使用fn.css方法即可。
jQuery("#ddd").css("height")
fn的css方法实际取的是dom对象的style中的height,与下面的代码是等效的。
jQuery("#ddd")[0].style.height
这会导致结果会带有px(输出50.5px),不过这不是什么问题。
升级版本
高版本的jquery已经修复了这个问题,至少从3.2.1开始是没问题的(比它低的手里没有,就没做测试)。
官方文档:https://api.jquery.com/height/
The difference between .css( “height” ) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element’s height needs to be used in a mathematical calculation.
简单翻译一下就是,.css( “height” )和.height()返回的值除了css会带有px以外,是一样的。
查看3.4.1的源码,会发现jQuery.css方法获取高度时会使用curCSS( elem, name, styles );
,而这个方法中就是使用dom对象的style属性获取的。