如:
復制代碼 代碼如下:
<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