uniapp获取屏幕宽度时 获取不到移动设备中内容盒子宽度

首先 :我使用的是uniapp+ vue3语法:
问题: 我出现这个问题是IOS 设备发现的,data.boxWidth为0
代码:

 const initCreated = () => {
      const query = uni.createSelectorQuery().in(instance.proxy);
      const el = query.select("#readView").boundingClientRect(rect => {
        console.log('rect.width', rect.width)
        if (rect.width)
        {
          const width = rect.width - 20;
          // const height = rect.height - 20;
          data.boxWidth = width;
          // data.height = height;
        }
      }).exec();

      console.log('data.boxWidth', data.boxWidth)
    }

原因:
使用了 uni.createSelectorQuery() 来获取元素的宽度,然后在回调函数中设置 data.boxWidth 的值。然而,uni.createSelectorQuery() 方法是异步的,也就是说,它会在后台进行元素查询,然后在执行 .exec() 后才会触发回调函数。

因此,在你的代码中,第一个 console.log(‘data.boxWidth’, data.boxWidth) 实际上会在异步操作之前执行,所以它会打印出初始值(可能是 undefined 或者之前的值)。而第二个 console.log(‘rect.width’, rect.width) 是在回调函数中,它会在异步操作完成后执行,所以它能够正确地获取到元素的宽度。

解决:
别单独封装一个函数了,直接在使用盒子宽度的代码处(执行操作),就放在' // 在这里进行需要使用盒子宽度的操作'这里执行获取到宽度后的代码就行。

这样可以确保在正确获取到宽度后再进行后续操作,避免了异步操作的影响。

const initCreated = () => {
  const query = uni.createSelectorQuery().in(instance.proxy);
  query.select("#readView").boundingClientRect(rect => {
    console.log('rect.width', rect.width)
    if (rect.width) {
      const width = rect.width - 20;
      // const height = rect.height - 20;
      data.boxWidth = width;
      // data.height = height;

      console.log('data.boxWidth', data.boxWidth);
      // 在这里进行需要使用盒子宽度的操作
    }
  }).exec();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值