小程序動態獲取元素高度報錯VM14689:1 thirdScriptError Cannot read property 'height' of null;at SelectorQuery callback function TypeError: Cannot read property 'height' of null


 小程序動態獲取元素高度報錯

 

 

 

原因是因為該元素此刻是隱藏不顯示的。

那么怎么判斷避免這個錯誤呢?

e g:

id為c3的元素存在,id為c4的元素不存在。

 wx.createSelectorQuery().select('#c3').boundingClientRect(function (rect) {
      console.log(rect)//{id:...}
    }).exec()

 wx.createSelectorQuery().select('#c4').boundingClientRect(function (rect) {
      console.log(rect)//null
  }).exec()

打印結果如下:

 

 

所以,當獲取某個屬性的時候,我們要先判斷 rect 對象存在不存在就可以了,例如我們獲取某個元素高度的時候,就可以如下來判斷:

let h = rect?rect.height:0

這樣就不會報錯了。

希望這篇文章對你有所幫助!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM