jquery获取高度时无法获取小数的问题

<!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属性获取的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值