uniapp使用createSelectorQuery,boundingClientRect获取宽度和高度不准确的可用的解决方案

场景展示:

uniapp使用createSelectorQuery,boundingClientRect获取宽度和高度不准确的可用的解决方案,正常来说,使用下面的代码是可以正确获得宽高的,但是里面含有图片,在图片没有加载完的情况下,我们可以想像一下,计算出来的结果肯定是不对的。而且我也在网上找了不少的解决方案。大多数是说有padding和margin,再使用getComputedStyle这样的函数。显得都太复杂,经过摸索实验,最终的解决方案比较简单:

  const query = uni.createSelectorQuery().in(this);
                query.select("#box-bottom").boundingClientRect();
                query.select("#box-title").boundingClientRect();
                query.exec(function (res) {
                    var ttheight = 0;
                    for (var i in res) {
                        ttheight += res[i].height;
                    }
                    that.midbox.height = lsktl.ci.windowHeight - ttheight-30;
                });

如下图,我想要计算box-title和box-bottom的高度,然后再确认中心的可滚动部分,其中头部和底部都有id="box-title"和id="box-bottom"的id的两个盒子。

就是给要计算的宽高的盒子加上:key="key",这样的话,就可以正确得到宽和高了。

代码如下:

  that.kklist.bottom=lsktl.rndstr();
            that.kklist.title=lsktl.rndstr();
            that.$nextTick(function () {
                const query = uni.createSelectorQuery().in(this);
                query.select("#box-bottom").boundingClientRect();
                query.select("#box-title").boundingClientRect();
                query.exec(function (res) {
                    var ttheight = 0;
                    for (var i in res) {
                        ttheight += res[i].height;
                    }
                    that.midbox.height = lsktl.ci.windowHeight - ttheight-30;
                });
            });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值