小程序動態獲取元素高度報錯
原因是因為該元素此刻是隱藏不顯示的。
那么怎么判斷避免這個錯誤呢?
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
這樣就不會報錯了。
希望這篇文章對你有所幫助!