如何解決Firefox在用offsetHeight擷取div的高度時為0

來源:互聯網
上載者:User
Firefox在需要擷取p的高度時,往往需要用到offsetHeight,有時會碰到offsetHeight擷取到為0的現象,下面為大家介紹下比較實用的解決方案,感興趣的朋友可參考下

Firefox在需要擷取p的高度時,往往需要用到offsetHeight,有時會碰到offsetHeight擷取到為0的現象,

在使用IE或者Firefox中,特別在目前p+css的方式,往往不定義p的高度,這是在添加p內容後,需要擷取p的高度時,往往需要用到offsetHeight。

在使用中,有時會碰到offsetHeight擷取到為0的現象,但如果你用各種JS調試工具調試,又能在對象中看到值(如果直接指向offsetHeight是沒值的,但如果是對象查看是有值的,在調試器中斷行符號查看對象就已經重新整理對象了,所以有值。)

比如下面片段

代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script language='javascript'> window.attachEvent( "onload", function(){ _resizeScroll2();} ); window.onresize=function(){winresize();}; function _resizeScroll2(){ var html1 = '<p id="pcj" style="margin-top:15px;font-size:10px;width:400px;">' + '<p style="float:left;width:50px;">測試</p>' + '<p style="float:left;width:320px;">danielinbiti</p>' + '</p>' + '<p id="pcj2" style="margin-top:15px;font-size:10px;width:400px;">' + '<p style="width:320px;">danielinbiti</p>' + '</p>' document.getElementById('outer').innerHTML=html1; document.getElementById('pcj2').style.display='none'; alert(document.getElementById('pcj2').offsetHeight); } </script> </head> <body> <p id='outer'></p> </body> </html>

如果擷取pcj的高度,那麼在onload中擷取到的是0。因為pcj下有float方式布局的。

這時如果p簡單,可以藉助隱藏層,比如這裡的pcj2,把float去掉後,擷取到的高度和pcj一樣高。

這裡有一個關鍵點就是float布局在ie是沒問題,但是對於Firefox它取到就為0了

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

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.