加载中...
  • 微信小程序 获取元素高度(获取元素节点信息)

    微信小程序开发中想要如h5一样获取元素的宽高值进行业务的功能实现,一开始不知道怎么实现,翻看文档发现,微信官方提供了一个非常好的东西

    SelectorQuery wx.createSelectorQuery()

    示例代码

    1
    2
    3
    4
    5
    6
    7
    const query = wx.createSelectorQuery()
    query.select('#the-id').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
    res[0].top // #the-id节点的上边界坐标
    res[1].scrollTop // 显示区域的竖直滚动位置
    })

    1.如果高度要px单位的话:

    1
    2
    3
    4
    5
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect=>{
    let height = rect.height;
    console.log(height);
    }).exec();

    2.如果高度要rpx单位的话,那么可以用宽高比换算获得:(以下的750是该元素的宽度,单位是rpx的)

    1
    2
    3
    4
    5
    6
    7
    8
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect=>{
    let clientHeight = rect.height;
    let clientWidth = rect.width;
    let ratio = 750 / clientWidth;
    let height = clientHeight * ratio;
    console.log(height);
    }).exec();

    3.在页面渲染完成OnReady回调 获取元素高度时,如果不加定时器,获取的元素的高度还是没渲染完异步数据前的高度。故需要加定时器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    onReady () {
    setTimeout(() => {
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect=>{
    let height = rect.height;
    console.log(height);
    }).exec();
    }, 300)
    }
    上一篇:
    React Hooks+Typescript 中 父组件调用子组件方法.
    下一篇:
    浅拷贝和深拷贝
    本文目录
    本文目录