小程序动态获取元素高度报错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

这样就不会报错了。

希望这篇文章对你有所帮助!

猜你喜欢

转载自www.cnblogs.com/helena000/p/12515409.html