css值轉換成數值請拋棄parseInt

來源:互聯網
上載者:User

如: 複製代碼 代碼如下:<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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.