当前位置: 首页 > news >正文

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();
}
http://www.lryc.cn/news/121455.html

相关文章:

  • 篇十二:代理模式:控制对象访问
  • P1657 选书
  • 代码随想录第46天 | 139. 单词拆分、多重背包
  • Unreal View Model结合GAS使用
  • Spring-Cloud-Loadblancer详细分析_2
  • uniapp 左右滑动切换页面并切换tab
  • FinClip 支持小程序维度域名配置;桌面端体验活动进行中
  • 已有公司将ChatGPT集成到客服中心以增强用户体验
  • 108. 将有序数组转换为二叉搜索树
  • 视频分辨率: UXGA/SVGA/VGA/QVGA/QQVGA
  • Leecode力扣27数组移除元素
  • 百度云盘发展历程与影响
  • SpringBoot复习:(33)WebMvcAutoconfiguration内部静态类WebMvcAutoConfigurationAdapter
  • f1tenth仿真2
  • exec族函数
  • dbm与mw转换
  • 【Linux】多线程之单例模式
  • Vision Transformer模型入门
  • 如何使用 Go 获取 URL 的参数,以及使用时的问题
  • Linux驱动-基于QT控制LED灯
  • 布隆过滤器的原理和应用场景
  • ElasticSearch学习
  • 软件测试基础篇——Redis
  • 大数据扫盲(1): 数据仓库与ETL的关系及ETL工具推荐
  • spring的aop动态代理对象注入时机
  • idea集成svn
  • RedisDesktopManage
  • 《Vue.js实战》——基础篇(1)
  • R语言 列表中嵌套列名一致的多个数据框如何整合为一个数据框
  • PyQt5利用QTextEdit控件输入多行文本