场景展示:
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;
});
});