如:
<div id="demo" style="width:24px"></div>
<script>
var elem = document.getElementById('demo'),
width = elem.style.width;
alert(parseInt(width));// 24
</script>
可是如果css值是这样呢:
<div id="demo" style="opacity:0.5"></div>
<script>
var elem = document.getElementById('demo'),
opacity = elem.style.opacity;
alert(parseInt(opacity));// 0
</script>
以上显然parseInt()会出错,哪怕是'.5′这样的值,如果换成parseFloat()将能得到正确的结果:
<div id="demo" style="opacity:0.5"></div>
<script>
var elem = document.getElementById('demo'),
opacity = elem.style.opacity;
alert(parseFloat(opacity));// 0.5
两者有何区别?
parseInt() 返回一个整数
parseFloat() 返回一个浮点数
进一步了解
parseInt 和
parseFloat