Posted in Javascript onOctober 24, 2011
如:
<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
css值转换成数值请抛弃parseInt
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@